Sub topic 12
Putting a Representation to Work: Breadth-First Traversal
This chapter assumes you can read Python, know that a queue is first-in, first-out, and know that a set gives constant-time average membership checks. It also assumes you have seen the adjacency list from the previous chapter.
What breadth-first search does
Breadth-first search (BFS) visits every vertex reachable from a start vertex. It visits them in order of distance, measured in edges. First it visits the start, then all of its neighbors, then all of their unvisited neighbors, and so on.
The algorithm needs one operation from the graph: "give me the neighbors of this vertex." An adjacency list answers that by returning a stored list, so it is the natural fit.
The working model
BFS keeps two collections:
- A queue holds vertices that have been discovered but not yet processed. Taking from the front gives the order-by-distance behavior.
- A seen set holds every vertex that has ever been added to the queue. It stops the search from revisiting vertices and from looping forever on cycles.
The code
from collections import deque
def bfs(graph, start):
seen = {start}
order = []
queue = deque([start])
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": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"]}
print(bfs(graph, "A")) # ['A', 'B', 'C', 'D']Trace the run. The queue starts as [A]. Processing A adds B and C. Processing B finds A already seen and adds D. Processing C finds A and D already seen, so it adds nothing. Processing D adds nothing. The result is ['A', 'B', 'C', 'D'].
Cost
Each vertex enters the queue at most once, so the outer loop runs at most V times. Each vertex's neighbor list is scanned once, so the inner loop does work proportional to the sum of the list lengths. That sum is E for a directed graph and 2E for an undirected one. The total is O(V + E).
The representation changes this cost. With an adjacency matrix, finding a vertex's neighbors means scanning a whole row of V entries, so BFS costs O(V²) no matter how few edges exist. For a sparse graph, the adjacency list is much cheaper.
Common errors
- Marking vertices as seen when you pop them instead of when you push them. The same vertex can then enter the queue several times. The output may still look right, but the work grows and the queue can get large.
- Using a list with
pop(0)as the queue. Removing from the front of a Python list takes O(n) time. Usecollections.deque, wherepopleft()is O(1). - Forgetting to record both directions of an undirected edge. If B's list does not contain A, the search may not behave as you expect.
- Assuming BFS reaches every vertex. It reaches only the start's connected component. For a disconnected graph, run BFS again from each unseen vertex.
- Indexing a missing vertex. With a plain dictionary,
graph[node]raisesKeyErrorfor a vertex that has no entry. Give every vertex an entry, even if its list is empty.
BFS on an implicit graph
BFS works the same way when the graph is not stored. Replace graph[node] with a function that computes neighbors, such as the grid neighbor generator from the previous chapter. Cells can be (row, col) tuples, which are hashable and so work in the seen set.
Exercise
A graph has 1,000 vertices and 2,000 undirected edges. Roughly how many neighbor-list entries does BFS scan on an adjacency list, and why is an adjacency matrix a worse choice here?
Show answer
About 4,000 entries, because each undirected edge appears in two lists (2E). An adjacency matrix would scan a full row of 1,000 entries for each of the 1,000 vertices, about 1,000,000 checks, even though most entries are 0.
Exercise
In the BFS code, what goes wrong if you move seen.add(neighbor) from the point where the neighbor is appended to the point where it is popped?
Show answer
A vertex can be appended to the queue more than once before it is popped. The traversal does redundant work and the queue grows larger than necessary.