Sub topic 3
The Breadth-First Search Algorithm
This chapter assumes you can read Python, know how lists, dictionaries, and sets work, and know what vertices and edges are. It also builds on the two previous chapters: graphs stored as adjacency lists, and collections.deque used as a first-in, first-out (FIFO) queue.
Breadth-first search (BFS) is a way to visit every vertex you can reach from a starting vertex, called the source. It works outward from the source. First it visits the source, then every neighbor of the source, then every neighbor of those neighbors, and so on. A queue keeps this order. Vertices found earlier are processed earlier, so BFS never runs ahead down one branch.
The loop in plain steps
BFS keeps two pieces of state:
- A queue of vertices that have been discovered but not yet processed.
- A visited set of every vertex that has ever been added to the queue.
The algorithm works like this:
- Put the source in the visited set and in the queue.
- While the queue is not empty, remove the vertex at the front.
- Process it, for example by recording it in the output.
- For each neighbor that is not yet in the visited set, add it to the visited set and append it to the back of the queue.
The code
from collections import deque
def bfs(graph, start):
visited = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs(graph, 'A')) # ['A', 'B', 'C', 'D', 'E', 'F']Tracing a run
Each row below is one pass through the while loop.
| Dequeued | Neighbors checked | Newly enqueued | Queue after |
|---|---|---|---|
| A | B, C | B, C | B, C |
| B | D | D | C, D |
| C | D, E | E | D, E |
| D | F | F | E, F |
| E | F | none | F |
| F | none | none | empty |
When C is processed, D is already in the visited set, so it is skipped. That check keeps each vertex from entering the queue more than once. The next chapter explains why the check must happen at enqueue time.
Common errors
- Using
list.pop(0)as the queue. It gives the right result, but each call shifts every remaining element, which costs O(n).deque.popleft()costs O(1). - Using
pop()instead ofpopleft(). This takes from the back, so the structure acts as a stack and you no longer get breadth-first order. - Forgetting to mark the source. If
visitedstarts empty, a cycle that leads back to the source puts it in the queue a second time. - Missing keys.
graph[node]raisesKeyErrorif a vertex with no outgoing edges has no entry. Give every vertex a key, even if its list is empty, as'F': []does above.
Exercise
Using the same graph, change the adjacency list for 'A' to ['C', 'B']. What does bfs(graph, 'A') return?
Show answer
['A', 'C', 'B', 'D', 'E', 'F']. C is dequeued first and enqueues D and E. When B is processed, D is already visited. D then enqueues F, and E finds F already visited.
Exercise
A teammate swaps queue.popleft() for queue.pop() in the code above. What order does the function return for the original graph, and why?
Show answer
['A', 'C', 'E', 'F', 'D', 'B']. pop() removes the most recently added vertex, so the queue acts as a stack. After A, the stack holds B and C, and C comes off first. C adds E (D was not yet visited, so D is added too, giving [B, D, E]). E comes off next and adds F. Then F, D, and B come off. The traversal goes deep before it goes wide.