Introduction
Imagine you want to show connections between places or people. Sometimes the connection goes both ways, and sometimes it only goes one way. Understanding these two types of connections helps us model many real-world problems.
Jump into concepts and practice - no test required
Think of a neighborhood with streets. Some streets allow cars to go both ways, like undirected connections. Other streets are one-way, allowing cars to go only in one direction, like directed connections.
Undirected Graph Directed Graph
A─────B A ──▶ B
\ /
C C
class Graph: def __init__(self, directed=False): self.directed = directed self.adj_list = {} def add_node(self, node): if node not in self.adj_list: self.adj_list[node] = [] def add_edge(self, start, end): self.add_node(start) self.add_node(end) self.adj_list[start].append(end) if not self.directed: self.adj_list[end].append(start) def display(self): for node, neighbors in self.adj_list.items(): print(f"{node} -> {neighbors}") # Undirected graph example g1 = Graph(directed=False) g1.add_edge('A', 'B') g1.add_edge('A', 'C') g1.display() print('---') # Directed graph example g2 = Graph(directed=True) g2.add_edge('A', 'B') g2.add_edge('A', 'C') g2.display()
A and B?[(1, 2), (2, 3), (3, 1)], what is the result of checking if there is a path from vertex 3 to vertex 2?edges = [(1, 2), (2, 3), (3, 1)] used as is for an undirected graph.