Sub topic 11
Traversing a Graph with Breadth-First Search
Breadth-first search (BFS) visits every vertex reachable from a starting vertex. It goes level by level: first the start, then its neighbors, then their neighbors. This chapter assumes you can read an adjacency list stored as a dictionary of dictionaries, and that you know how a queue behaves (first in, first out).
The idea
BFS keeps a queue of vertices that have been discovered but not yet processed. It repeats three steps:
- Remove the vertex at the front of the queue.
- Look at each of its neighbors.
- Add each neighbor that has not been seen before to the back of the queue.
Because the queue is first in, first out, every vertex that is one edge from the start is processed before any vertex that is two edges away. That level-by-level order is what makes BFS useful.
A runnable implementation
This code reuses the add_edge helper from the adjacency-list chapter. It is repeated here so the example runs on its own.
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] = weight
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
g = {}
for u, v in [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("D", "E")]:
add_edge(g, u, v)
print(bfs(g, "A")) # ['A', 'B', 'C', 'D', 'E']The seen set is added to at the moment a vertex is queued, not when it is dequeued. D is a neighbor of both B and C. If you marked vertices only when dequeued, D would be queued twice.
Counting edges from the start
Storing a distance instead of a plain set gives the minimum number of edges from the start to every reachable vertex. The dictionary doubles as the seen set.
def bfs_distances(graph, start):
dist = {start: 0}
queue = deque([start])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in dist:
dist[v] = dist[u] + 1
queue.append(v)
return dist
print(bfs_distances(g, "A")) # {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 3}A vertex is first discovered along a path with the fewest edges, so its recorded count is the smallest possible. This counts edges only. It ignores weights.
Cost
With an adjacency list, each vertex is queued at most once, and each vertex's neighbors are scanned once. The running time is O(V + E), where V is the number of vertices and E the number of edges. Memory is O(V) for the queue and the seen set. With an adjacency matrix, scanning a vertex's neighbors costs O(V), so the whole traversal costs O(V²).
Behavior on each graph type
- Undirected: BFS reaches exactly the connected component of the start vertex.
- Directed: BFS follows edge directions, so it reaches only the vertices reachable from the start. Some vertices may be missed even in a "connected" graph.
- Disconnected: vertices outside the start's component never appear. To visit everything, call BFS from each vertex not yet seen.
Common errors
| Error | Result | Fix |
|---|---|---|
| Marking seen on dequeue | Duplicate queue entries, extra work | Mark when queuing |
| Using `list.pop(0)` as the queue | Each removal is O(n) | Use `deque.popleft()` |
| Expecting all vertices from one call | Other components are missing | Loop over all vertices |
| Treating edge counts as weighted distances | Wrong shortest paths | Use Dijkstra |
Exercise
A directed graph has edges A→B and C→B only. What does bfs(graph, "B") return, and why?
Show answer
It returns ['B']. B has no outgoing edges, so no neighbor is queued. BFS follows edge directions, and A and C can reach B but B cannot reach them.