Sub topic 9
Graphs: modeling relationships and traversals
This chapter assumes you know Python lists, dictionaries and sets, and have a rough idea of Big-O. It also assumes you have seen the hash table and queue chapters. Graphs reuse both.
What a graph models
A graph is a set of nodes connected by edges. Use one when the data is about relationships: roads between cities, links between pages, dependencies between tasks. Edges can be directed (one-way) or undirected (two-way), and they can carry a weight such as a distance.
The operations that matter are usually these:
- List the neighbors of a node.
- Check whether an edge exists between two nodes.
- Visit every node reachable from a start node.
- Find a path with the fewest edges.
Choosing a representation
Two representations cover most work. With V nodes and E edges:
| Representation | Memory | Neighbors of a node | Edge exists? | Best for |
|---|---|---|---|---|
| Adjacency list (dict of lists) | O(V + E) | O(degree) | O(degree) | Sparse graphs, traversals |
| Adjacency set (dict of sets) | O(V + E) | O(degree) | O(1) average | Sparse graphs with edge checks |
| Adjacency matrix (2D list) | O(V²) | O(V) | O(1) | Dense graphs, small V |
Most real graphs are sparse: each node touches only a few others. An adjacency list stores only the edges that exist, so it is the usual default. A matrix wastes memory on every missing edge. If you also need fast "is A connected to B?" checks, store neighbors in sets instead of lists.
graph = {
"a": ["b", "c"],
"b": ["d"],
"c": ["d"],
"d": [],
}
print(graph["a"]) # ['b', 'c']For an undirected graph, add each edge in both directions. Forgetting one direction is a common source of bugs.
Traversal: breadth-first search
Breadth-first search (BFS) visits nodes in order of distance from the start. It needs three structures, each chosen for one job:
- A dictionary for the adjacency list, so neighbor lookup is direct.
- A set for visited nodes, so the "seen before?" test is O(1) on average.
- A deque as the queue, so removing from the front is O(1). A list's
pop(0)shifts every element and costs O(n).
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return order
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs_order(graph, "a")) # ['a', 'b', 'c', 'd']Each node is queued once and each edge is examined once, so the total cost is O(V + E). Marking a node as seen when you enqueue it, not when you dequeue it, stops the same node from entering the queue twice. Because BFS expands level by level, the first time it reaches a node is along a path with the fewest edges.
Depth-first search and the container choice
Depth-first search (DFS) follows one path as far as it can before backing up. The traversal code is the same as BFS, except the container is a stack. Swap the deque's popleft() for pop() and you get DFS. The container decides the visiting order, so choose it based on what you need:
- Fewest edges to a target: BFS with a queue.
- Exhaustive exploration, cycle detection, or ordering tasks by dependency: DFS with a stack or recursion.
Python's recursion limit (about 1000 frames by default) can break recursive DFS on deep graphs. Use an explicit stack if paths can be long.
Common errors
- Skipping the visited set. On a graph with cycles, the traversal never ends.
- Using a list for the queue. It works on small inputs and becomes slow on large ones.
- Using a matrix for a sparse graph. A graph of 100,000 nodes would need 10 billion cells.
- Using
graph[node]for a node with no entry. Give every node a key, even with an empty list, or usegraph.get(node, []).
Exercise
A social network has 2 million users, and each user follows about 150 others. You need to list who a user follows and to test quickly whether user X follows user Y. Which representation fits, and why not a matrix?
Show answer
Use a dictionary mapping each user to a set of the users they follow. Listing neighbors costs O(degree), and the "follows" test is O(1) on average. The graph is sparse: about 300 million edges against 4 trillion possible pairs. A matrix would need O(V²) memory, which is far too large.