Sub topic 1
Representing Graphs for Traversal
Breadth-first search (BFS) spends most of its time answering one question: "what are the neighbors of this vertex?" How you store the graph decides how quickly that question gets answered. This chapter sets up the adjacency-list representation that every later chapter uses.
Prerequisites
This chapter assumes you can:
- Write basic Python, including functions and loops.
- Use lists, dictionaries, and sets.
- Use graph vocabulary: vertices, edges, directed and undirected graphs.
- Read Big-O notation, such as O(V + E).
The Running Example
The tutorial uses one small directed graph throughout. It has six vertices, A through F, and seven edges.
Three Ways to Store a Graph
| Representation | Storage | Find all neighbors of v | Check if edge u→v exists |
|---|---|---|---|
| Edge list | O(E) | O(E), scan every edge | O(E) |
| Adjacency matrix | O(V²) | O(V), scan a row | O(1) |
| Adjacency list | O(V + E) | O(deg(v)) | O(deg(v)) |
Traversal asks for all the neighbors of each vertex it reaches, and it almost never asks whether one particular edge exists. The adjacency list answers the neighbor question in time proportional to the vertex's degree, which is its number of outgoing edges. Adding up those degrees over all vertices is where BFS's O(V + E) bound comes from. A matrix would force O(V) work per vertex, or O(V²) in total, even for a sparse graph.
Building an Adjacency List in Python
In Python, a dictionary that maps each vertex to a list of its neighbors works well. Graphs often arrive as edge lists, so a small builder function helps:
def build_graph(vertices, edges, directed=False):
graph = {v: [] for v in vertices}
for u, v in edges:
graph[u].append(v)
if not directed:
graph[v].append(u)
return graph
edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'D'),
('C', 'E'), ('D', 'F'), ('E', 'F')]
directed = build_graph('ABCDEF', edges, directed=True)
print(directed)
# {'A': ['B', 'C'], 'B': ['D'], 'C': ['D', 'E'], 'D': ['F'], 'E': ['F'], 'F': []}
path = build_graph('ABC', [('A', 'B'), ('B', 'C')])
print(path)
# {'A': ['B'], 'B': ['A', 'C'], 'C': ['B']}The function creates a key for every vertex before it adds any edges. That way, a vertex with no outgoing edges, such as F, still appears with an empty list.
Common Errors
- Forgetting the reverse edge. An undirected edge {u, v} must be stored twice, once in u's list and once in v's. If you store it only once, the traversal can reach v from u but never u from v.
- Duplicate edges. If the input lists the same edge twice, the neighbor list holds it twice. BFS still gives correct results, but it does extra work. Deduplicate the input, or use sets of neighbors if order does not matter.
- Neighbor order. The order of each list decides the order in which a traversal discovers vertices. It never changes the distances BFS computes, but it can change which of several equally short paths gets returned. Expected outputs in this tutorial depend on the list order shown above.
- Unhashable vertices. Dictionary keys must be hashable. Grid cells should be tuples like (row, col), not lists.
Exercises
Exercise
You build the undirected graph with edges ('A', 'B') and ('B', 'C') but forget the line that adds the reverse edge. Which vertices are reachable from C, and why?
Show answer
Only C itself. Without the reverse edges, the stored lists are A: ['B'], B: ['C'], C: []. C has no outgoing neighbors, so a traversal that starts at C stops immediately, even though the undirected graph is connected.
Exercise
A social network has 1,000,000 users, and each user has about 200 friends. Roughly how many entries does an adjacency matrix need compared with an adjacency list?
Show answer
A matrix needs V² = 10^12 cells. An undirected adjacency list stores each friendship twice, so it holds about 1,000,000 × 200 = 2 × 10^8 neighbor entries plus 10^6 keys. That is about 5,000 times smaller, which is why sparse graphs use adjacency lists.