Sub topic 11
Traversing a Graph with Breadth-First Search
What this chapter assumes
You should know how to read a dictionary-of-dictionaries adjacency list, where graph[u] maps each neighbor of u to an edge weight. You should also know what a queue is, how a set gives constant-time membership tests, and the meaning of O(V + E). The helper below is the same one used earlier in this tutorial. It builds undirected graphs by default and directed graphs with directed=True.
from collections import deque
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weightThe idea
A traversal visits every vertex that can be reached from a starting vertex, each exactly once. Breadth-first search (BFS) does this in layers. It visits the start vertex first, then every vertex one edge away, then every vertex two edges away, and so on.
A queue produces this order. Vertices leave the queue in the order they entered it. Neighbors of the start enter before neighbors of those neighbors, so closer vertices are always processed first.
The diagram shows the example graph used in this chapter, with the layers BFS discovers from A.
The graph also has a second, separate part: F and G joined by one edge. BFS from A never reaches them.
g = {}
add_edge(g, "A", "B")
add_edge(g, "A", "C")
add_edge(g, "B", "D")
add_edge(g, "C", "D")
add_edge(g, "D", "E")
add_edge(g, "F", "G")The algorithm
def bfs(graph, start):
seen = {start}
order = []
queue = deque([start])
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
return order
print(bfs(g, "A")) # ['A', 'B', 'C', 'D', 'E']The loop works like this:
- Put the start vertex in the queue and in
seen. - Remove the vertex at the front of the queue and record it.
- For each neighbor not yet in
seen, add it toseenand to the back of the queue. - Repeat until the queue is empty.
Tracing the example gives this table. The queue column shows the queue after step 3.
| Vertex removed | New neighbors found | Queue afterward |
|---|---|---|
| A | B, C | B, C |
| B | D | C, D |
| C | none (D already seen) | D |
| D | E | E |
| E | none | empty |
F and G are absent from the result because no path leads from A to them.
Mark when queued, not when removed
The code adds a vertex to seen at the moment it enters the queue. Consider the alternative: marking only when a vertex is removed. In the trace above, D is a neighbor of both B and C. With late marking, D would be queued twice, once from each parent, before either copy is processed. In a dense graph a vertex can be queued once per incoming edge, and the work grows from O(V + E) toward much worse behavior on some graphs. Marking on entry guarantees each vertex is queued at most once.
Cost
With an adjacency list, each vertex is removed from the queue once, and each vertex's neighbor dictionary is scanned once. Every edge is therefore examined a constant number of times: twice in an undirected graph (once from each end) and once in a directed graph. The total is O(V + E) time. The seen set and the queue need O(V) extra space.
With an adjacency matrix, finding the neighbors of a vertex means scanning a whole row of length V. The total becomes O(V²), regardless of how few edges exist. This is one reason adjacency lists are the usual choice for traversal on sparse graphs.
The queue must be a deque. Using a plain list with pop(0) shifts every remaining element on each removal, which costs O(n) per call and can turn the traversal quadratic.
Distances and shortest paths by edge count
Because BFS finishes all vertices at distance k before any at distance k + 1, the first time it reaches a vertex is along a path with the fewest edges. We can record this by storing a distance and a parent for each vertex when we first see it.
def bfs_distances(graph, start):
dist = {start: 0}
parent = {start: None}
queue = deque([start])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in dist:
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return dist, parent
def path_to(parent, target):
if target not in parent:
return None
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
dist, parent = bfs_distances(g, "A")
print(dist) # {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 3}
print(path_to(parent, "E")) # ['A', 'B', 'D', 'E']
print(path_to(parent, "F")) # NoneHere dist doubles as the seen set. A vertex is "seen" once it has a distance. D could have been reached through B or C. Both paths have two edges, and the parent is B because B was processed first. When several shortest paths tie, BFS returns whichever its neighbor order finds first.
BFS is not Dijkstra's algorithm
BFS minimizes the number of edges, not the total weight. In the weighted graph from earlier chapters (A-B weight 4, A-C weight 1, C-B weight 2), BFS reaches B directly from A in one edge. That path costs 4, but the path through C costs 3. If every edge has the same weight, or you only care about hop count, BFS is correct and simpler. If weights differ, use Dijkstra's algorithm, covered later in this tutorial.
Directed graphs
BFS code does not change for directed graphs. The loop for v in graph[u] follows only outgoing edges, so the traversal finds what is reachable by following arrows.
d = {}
add_edge(d, "A", "B", directed=True)
add_edge(d, "C", "B", directed=True)
print(bfs(d, "A")) # ['A', 'B']
print(bfs(d, "B")) # ['B']
print(bfs(d, "C")) # ['C', 'B']C points to B, but A and C have no route to each other. Reachability in a directed graph is not symmetric: B is reachable from A, but A is not reachable from B.
Covering a disconnected graph
One BFS call reaches only one part of the graph. To find every connected component of an undirected graph, start a new BFS from each vertex not yet seen.
def components(graph):
seen = set()
result = []
for start in graph:
if start not in seen:
comp = bfs(graph, start)
seen.update(comp)
result.append(comp)
return result
print(components(g)) # [['A', 'B', 'C', 'D', 'E'], ['F', 'G']]Each vertex is visited by exactly one BFS, so the total cost stays O(V + E). This function is correct only for undirected graphs. On a directed graph it returns groups of reachable vertices that depend on the order of the starting points, which is not the same as strongly connected components.
Common errors
- Marking too late. Adding to
seenafterpopleftcauses duplicate queue entries. The output order may still look right on small graphs, which hides the bug. - Using a list as a queue.
list.pop(0)works but is O(n). Usedeque.popleft(). - Reading
graph[u]for a missing vertex. If a vertex appears only as a target and was never given an entry,graph[u]raisesKeyError. Theadd_edgehelper avoids this by always creatinggraph[v]. - Expecting full coverage. BFS from one start reaches only that vertex's reachable set. Unreached vertices are not an error.
- Treating hop count as cost. BFS distance is correct for edge count only, as shown above.
Exercise
Using the graph g above, which vertices does bfs(g, "D") visit, in order, and what is dist["A"] in bfs_distances(g, "D")?
Show answer
The neighbors of D in insertion order are B, C, E. B then adds A, so the order is ['D', 'B', 'C', 'E', 'A']. A is two edges from D (D to B to A), so dist["A"] is 2.
Exercise
A programmer changes bfs so that seen.add(v) happens right after u = queue.popleft() for the removed vertex, instead of when v is queued. The loop skips a removed vertex if it is already in seen. Is the visiting order still correct, and what is the downside?
Show answer
The visiting order is still correct, because the first removal of each vertex still follows layer order. The downside is that a vertex can be queued once per incoming edge before its first removal, so the queue can hold many duplicates and the work can exceed O(V + E). Marking when queued prevents this.