Sub topic 1
Representing Graphs for Traversal
Breadth-first search reads a graph through one operation: "give me the neighbors of this vertex." How you store the graph decides how fast that operation is, what output order you get, and which bugs show up. This chapter builds the adjacency-list representation that the rest of the tutorial uses, compares it with the alternatives, and covers the mistakes that most often break a traversal before it starts.
Prerequisites
This chapter assumes you can already:
- Write basic Python functions and loops.
- Use lists, dictionaries, and sets, including membership tests with
in. - Use graph vocabulary: vertices, edges, directed and undirected graphs, and the degree of a vertex.
- Read Big-O notation such as O(V + E) and O(V²), where V is the number of vertices and E the number of edges.
What a Traversal Needs from a Graph
A traversal algorithm asks the graph three kinds of questions:
- Which vertices exist?
- What are the neighbors of vertex
u? - Is there an edge from
utov?
BFS asks the second question once for every vertex it reaches. It almost never asks the third. A good representation for BFS therefore makes neighbor listing cheap and can be slower at edge lookups.
The Adjacency List
An adjacency list maps each vertex to the collection of its neighbors. In Python the usual form is a dictionary whose keys are vertices and whose values are lists.
Here is the same graph as a dictionary:
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
for neighbor in graph['C']:
print(neighbor) # D, then ELook at 'F': []. Vertex F has no outgoing edges, but it still has a key. A traversal that reaches F will run graph['F'], and without that key it raises KeyError. Every vertex that can appear as a neighbor must also appear as a key.
Building from an Edge List
Graphs usually arrive as a list of pairs, for example from a file or a database query. The function below converts pairs into an adjacency list. It handles both directed and undirected graphs and guarantees that every endpoint gets a key.
def build_adjacency(edges, directed=False, vertices=()):
graph = {v: [] for v in vertices}
for u, v in edges:
graph.setdefault(u, [])
graph.setdefault(v, [])
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')]
print(build_adjacency(edges, directed=True))
# {'A': ['B', 'C'], 'B': ['D'], 'C': ['D', 'E'], 'D': ['F'], 'E': ['F'], 'F': []}
print(build_adjacency(edges))
# {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D', 'E'],
# 'D': ['B', 'C', 'F'], 'E': ['C', 'F'], 'F': ['D', 'E']}The function makes three deliberate choices:
- An undirected edge is stored twice, once in each direction. BFS on an undirected graph only works if you can walk from either end, so
{u, v}becomesu → vandv → u. - The
verticesparameter lets you include isolated vertices, which have no edges and would never appear in the edge list. This matters when you count connected components, because an isolated vertex is a component on its own. setdefaultcreates the empty list for the target vertexvtoo, so sinks such as F always get a key.
The defaultdict Trap
collections.defaultdict(list) looks like a shortcut, and it is fine for building a graph. Reading from it during traversal causes trouble: looking up a missing key silently creates that key.
from collections import defaultdict
g = defaultdict(list)
g['A'].append('B')
print(len(g)) # 1 (B was never added as a key)
print('B' in g) # False
_ = g['Z'] # a typo or stray lookup
print(len(g)) # 2 (Z now exists as a vertex)Two bugs come out of this. Sinks like B are missing from the key set, so any code that loops over graph to visit every vertex skips them. And stray lookups add phantom vertices that inflate counts. A safe pattern is to build with defaultdict and then convert with dict(g) after making sure every neighbor has a key.
Validating a Graph
A one-line check catches the missing-key problem before BFS runs:
def missing_vertices(graph):
return {v for nbrs in graph.values() for v in nbrs if v not in graph}
print(missing_vertices({'A': ['B'], 'B': []})) # set()
print(missing_vertices({'A': ['B']})) # {'B'}Alternatives: Adjacency Matrix and Edge List
An adjacency matrix is a V × V grid where matrix[i][j] is 1 if there is an edge from vertex i to vertex j. It needs integer indices, so string names have to be mapped to positions first:
def to_matrix(graph):
names = list(graph)
index = {name: i for i, name in enumerate(names)}
n = len(names)
matrix = [[0] * n for _ in range(n)]
for u, nbrs in graph.items():
for v in nbrs:
matrix[index[u]][index[v]] = 1
return names, matrix
graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D', 'E'],
'D': ['F'], 'E': ['F'], 'F': []}
names, matrix = to_matrix(graph)
for name, row in zip(names, matrix):
print(name, row)
# A [0, 1, 1, 0, 0, 0]
# B [0, 0, 0, 1, 0, 0]
# C [0, 0, 0, 1, 1, 0]
# D [0, 0, 0, 0, 0, 1]
# E [0, 0, 0, 0, 0, 1]
# F [0, 0, 0, 0, 0, 0]Listing a vertex's neighbors now means scanning its whole row, which takes V steps no matter how few edges it has. An edge list, the raw list of pairs, is worse still: finding neighbors means scanning every edge.
| Representation | Space | List neighbors of u | Test edge u → v |
|---|---|---|---|
| Adjacency list (lists) | O(V + E) | O(deg(u)) | O(deg(u)) |
| Adjacency list (sets) | O(V + E) | O(deg(u)) | O(1) average |
| Adjacency matrix | O(V²) | O(V) | O(1) |
| Edge list | O(E) | O(E) | O(E) |
Most real graphs are sparse, meaning E is much smaller than V². A social network with a million users and a few hundred friends each would need 10¹² matrix cells but only a few hundred million list entries. Because BFS lists neighbors once per vertex, the adjacency list gives a total cost proportional to V + E. A later chapter derives that bound. A matrix forces V² work on BFS even when the graph has almost no edges.
Lists or Sets for Neighbors?
Storing neighbors in sets makes v in graph[u] fast and removes duplicate edges automatically. The cost is ordering. BFS visits neighbors in the order the collection yields them, and in Python:
- Lists keep insertion order, so the traversal order is the same on every run.
- Sets of strings have an order that depends on hash randomization, so
bfs(graph, 'A')can print a different visit order each time you run the program.
The shortest distances BFS computes stay the same either way. The visit order and the particular shortest path returned can change. Tests that compare exact output will then fail at random. Use lists unless you need fast edge tests, and if you use sets, sort neighbors when you need reproducible output.
Duplicate edges in a list are harmless for correctness, because the visited check covers them. They do cost extra work proportional to the number of duplicates.
Weighted and Implicit Graphs
Two variations appear later in the tutorial.
Weighted adjacency lists store (neighbor, weight) pairs. The 0-1 BFS chapter uses this form:
weighted = {
'A': [('B', 1), ('C', 0)],
'B': [('D', 0)],
'C': [('B', 0), ('D', 1)],
'D': [],
}
for v, w in weighted['A']:
print(v, w) # B 1, then C 0Implicit graphs have no stored edges at all. A function computes neighbors on demand. A maze grid, the states of a puzzle, or the words one letter away from a given word are all examples. Since BFS only needs neighbor listing, any function with the shape neighbors(u) -> iterable can replace graph[u]:
def neighbors(n):
return [m for m in (n + 1, n * 2) if m <= 20]
print(neighbors(5)) # [6, 10]
print(neighbors(15)) # [16]Implicit graphs can be huge or infinite, so you never build them in full. The traversal creates vertices only as it reaches them.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError` during traversal | A sink vertex has no key | Use `setdefault` for both endpoints and run `missing_vertices` |
| Results differ by start vertex in an undirected graph | Edges stored in one direction only | Append both `u → v` and `v → u` |
| Vertex count too high | `defaultdict` lookups created phantom keys | Convert to `dict` before traversal |
| Visit order changes between runs | Neighbors stored in sets | Use lists, or sort neighbors |
| Isolated vertices missing | Vertices built only from edges | Pass the full vertex set when building |
Exercise
You build an undirected adjacency list from the edges [(1, 2), (2, 3), (4, 4)] using build_adjacency. What dictionary do you get, and what is unusual about vertex 4?
Show answer
{1: [2], 2: [1, 3], 3: [2], 4: [4, 4]}. The self-loop (4, 4) is stored twice because the undirected branch appends both directions to the same list. BFS handles it correctly, since 4 is already visited when its own entries are examined, but degree counts become wrong. If you need correct degrees, skip the reverse append when u == v.
Exercise
Write a function is_symmetric(graph) that returns True when every edge u → v in an adjacency list has a matching v → u, which is the property an undirected graph must have. Test it on {'A': ['B'], 'B': ['A']} and {'A': ['B'], 'B': []}.
Show answer
def is_symmetric(graph): return all(u in graph.get(v, ()) for u, nbrs in graph.items() for v in nbrs). It returns True for the first graph and False for the second, because B has no edge back to A. Using graph.get(v, ()) avoids a KeyError when v has no key.
Exercise
A graph has 10,000 vertices and 30,000 edges. Roughly how many cells does an adjacency matrix need, compared with entries in a directed adjacency list? Which would you use for BFS?
Show answer
The matrix needs 10,000² = 100,000,000 cells. The adjacency list needs 10,000 keys plus 30,000 neighbor entries, about 40,000 items. BFS over the matrix also costs about 10⁸ row-scan steps, against about 4 × 10⁴ for the list. Use the adjacency list.