Graphs
After this lesson, you will be able to:
- Describe a graph with the words vertex, edge, directed, weighted, degree, cycle, sparse and dense
- Store a graph as an adjacency list, and know when a matrix or an edge list is the better choice
- Write BFS and DFS, and pick between them by the question you are asking
- Find the fewest-edges route between two vertices with BFS and rebuild the path
- Count the connected components of a graph with one traversal per piece
- State the time and space of each traversal, and the reason behind them
Before you start
#Graph Representations
Here is the graph we use for the whole lesson. It is undirected and weighted. The number on each line is its weight. BFS and DFS ignore the weights. The Shortest Paths lesson uses them.
D
|
3
|
A --4-- B --1-- E
| |
2 2
| |
C ------5------ F
from collections import defaultdict
# --- Adjacency List (best for sparse graphs) ---
# Space: O(V + E)
# Check if an edge exists: O(degree of the vertex)
# Visit all neighbors: O(degree of the vertex)
graph_list: dict[str, list[str]] = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
# Weighted adjacency list: each neighbor comes with the edge weight, {node: [(neighbor, weight)]}
weighted_graph: dict[str, list[tuple[str, int]]] = {
"A": [("B", 4), ("C", 2)],
"B": [("A", 4), ("D", 3), ("E", 1)],
"C": [("A", 2), ("F", 5)],
"D": [("B", 3)],
"E": [("B", 1), ("F", 2)],
"F": [("C", 5), ("E", 2)],
}
# --- Adjacency Matrix (best for dense graphs) ---
# A table with one row and one column per vertex. 1 means "there is an edge".
# Space: O(V²)
# Check if an edge exists: O(1)
# Visit all neighbors: O(V)
# For vertices A, B, C, D, E, F (row = from, column = to)
adj_matrix = [
[0, 1, 1, 0, 0, 0], # A: B, C
[1, 0, 0, 1, 1, 0], # B: A, D, E
[1, 0, 0, 0, 0, 1], # C: A, F
[0, 1, 0, 0, 0, 0], # D: B
[0, 1, 0, 0, 0, 1], # E: B, F
[0, 0, 1, 0, 1, 0], # F: C, E
]
# --- Edge List: every edge once, in one list ---
# Handy when you need to sort the edges by weight.
edges: list[tuple[str, str, int]] = [
("A", "B", 4),
("A", "C", 2),
("B", "D", 3),
("B", "E", 1),
("C", "F", 5),
("E", "F", 2),
]| Representation | Space | Edge Lookup | Iterate Neighbors | Best For |
|---|---|---|---|---|
| Adjacency List | O(V+E) | O(degree) | O(degree) | Sparse graphs (most real-world) |
| Adjacency Matrix | O(V²) | O(1) | O(V) | Dense graphs, fast edge checks |
| Edge List | O(E) | O(E) | O(E) | Input format, sorting edges by weight |
A social network has 1 billion users averaging 200 friends each. Which representation fits, and what does the other one cost?
#Graph Traversal: BFS and DFS
Watch each one run before you read the code. The viewers draw their own example graph, with eight vertices, but the rules are exactly the ones above.
Step through BFS and watch the queue grow and shrink. Vertices light up ring by ring, nearest first.
Step through DFS and watch it follow one path to its end before backing up. Compare the visiting order with BFS on the same kind of graph.
Now the code. Both functions cost O(V + E): each vertex is visited once and each edge is looked at a constant number of times.
from collections import deque
def bfs(graph: dict, start: str) -> list[str]:
"""Breadth-first search: explores level by level. O(V+E).
Uses a queue (FIFO). Finds the fewest-edges route in unweighted graphs.
"""
visited: set[str] = {start}
queue: deque[str] = deque([start])
order: list[str] = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
def bfs_shortest_path(graph: dict, start: str, end: str) -> list[str] | None:
"""BFS to find the shortest path (fewest edges) between two nodes.
Remember which node each node was reached from, to rebuild the path.
"""
if start == end:
return [start]
parent: dict[str, str | None] = {start: None} # doubles as the visited set
queue: deque[str] = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph.get(node, []):
if neighbor not in parent:
parent[neighbor] = node
if neighbor == end:
# Walk back through the parents, then flip the list.
path = [end]
while parent[path[-1]] is not None:
path.append(parent[path[-1]])
return path[::-1]
queue.append(neighbor)
return None # no path exists
def dfs_iterative(graph: dict, start: str) -> list[str]:
"""Depth-first search (iterative, using explicit stack). O(V+E).
Goes as deep as possible before backing up. Useful for finding cycles,
ordering tasks, and finding all connected pieces.
"""
visited: set[str] = set()
stack: list[str] = [start]
order: list[str] = []
while stack:
node = stack.pop() # LIFO: the newest vertex goes first, so we go deep
if node not in visited:
visited.add(node)
order.append(node)
for neighbor in reversed(graph.get(node, [])):
if neighbor not in visited:
stack.append(neighbor)
return order
def dfs_recursive(graph: dict, start: str,
visited: set | None = None) -> list[str]:
"""Depth-first search (recursive). O(V+E).
Cleaner than iterative for problems that naturally recurse,
like finding all paths or generating combinations.
"""
if visited is None:
visited = set()
order: list[str] = []
def visit(node: str) -> None:
visited.add(node)
order.append(node) # one shared list, so nothing is copied
for neighbor in graph.get(node, []):
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
# Example graph: the same graph as the picture at the top of this lesson,
# without the weights (A-B, A-C, B-D, B-E, C-F, E-F)
g = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
print("BFS from A:", bfs(g, "A")) # A, B, C, D, E, F
print("DFS from A:", dfs_iterative(g, "A")) # A, B, D, E, F, C
print("Fewest edges A to F:", bfs_shortest_path(g, "A", "F")) # ['A', 'C', 'F']def count_connected_components(graph: dict) -> int:
"""Count the number of connected components using DFS. O(V+E)."""
all_nodes = set(graph.keys())
visited: set[str] = set()
components = 0
for node in all_nodes:
if node not in visited:
dfs_recursive(graph, node, visited)
components += 1
return componentspieces = {"A": ["B"], "B": ["A"], "C": ["D"], "D": ["C"], "E": []}
print(count_connected_components(pieces))
# Output:
# 3DFS from A on the example graph: the recursive call tree (A calls B, B calls D then E, E calls F, F calls C)
Step through the recursive calls and returns to watch the call tree grow, results fill in, and the call stack change.
A recursion call tree for the supplied function, shown above its source code with a call stack panel beside it. It starts at step 0 with an empty tree and empty stack; each step adds a call or fills in a return value, until the tree is complete.
def dfs(graph, node, visited):
visited.add(node)
for nbr in graph[node]:
if nbr not in visited:
dfs(graph, nbr, visited)Watch the call stack: it grows as DFS goes deep (A, B, E, F, C is five calls deep) and shrinks on the way back. That depth is the most calls waiting at once. A graph with a very long path can pass Python's default limit of about 1000 waiting calls. The iterative version, with a stack of its own, avoids that limit.
BFS and DFS differ mainly in one line: BFS uses `queue.popleft()`, DFS uses a stack (or recursion). Which one finds the route with the fewest edges in an unweighted graph, and why does the other not?
#Code Playground: Five Graph Problems
Five problems, from easy to hard. Every one uses the same small town: a loop of three vertices with a tail, a separate pair, and one vertex alone. Problem 4 has a bug for you to find.
Tests: Expected output: line 1 is {'A': 2, 'B': 2, 'C': 3, 'D': 1, 'E': 1, 'F': 1, 'G': 0}. Line 2 is 2 -1. Line 3 is 3. Line 4 is ['A', 'B', 'C', 'D'] (the bug prints C and D twice). Line 5 is True False.
#Key Takeaways
- An adjacency list is a dict of lists, and that is the whole representation:
{node: [neighbors]}. A matrix only wins when the graph is dense or you need O(1) "is there an edge?" - BFS finds the fewest-edges route in an unweighted graph. Use
collections.deque(popleft is O(1)), neverlist.pop(0)(O(n)) - DFS goes as deep as it can before backing up. Use it to explore everything reachable, to find cycles, and to count components
- Both walks cost O(V + E) time and O(V) extra space, because each vertex is visited once and each edge is looked at a constant number of times
- Mark a vertex visited when you put it in the queue or stack, not when you take it out
- Cheapest routes with weights, and build orders, are in the Shortest Paths lesson. Joining groups as edges arrive is in the Union-Find lesson
You need the shortest route between two stations on a map where every hop takes the same time. Which traversal answers it, and why?