Sub topic 3
The Breadth-First Search Algorithm
This chapter assumes you can read Python and use lists, dictionaries, and sets. It also assumes you know basic graph terms (vertex, edge, directed, undirected) and Big-O notation. Earlier chapters covered how to store a graph as an adjacency list and why a FIFO queue built on collections.deque is the right container. This chapter combines the two into the full algorithm. You will trace it step by step, look at what it guarantees, and see the mistakes that break it most often.
What BFS Does
Breadth-first search (BFS) starts at one vertex, called the source, and visits every vertex reachable from it. It first visits all vertices one edge away from the source, then all vertices two edges away, and so on. Two pieces of state drive the search:
- A queue of vertices that have been discovered but not yet processed. This set of vertices is often called the frontier.
- A visited set of vertices that have already been discovered, so that no vertex is discovered twice.
Each step of the loop removes the oldest vertex from the front of the queue and looks at its neighbors. Any neighbor not seen before goes into the visited set and onto the back of the queue. Because the oldest entry always comes out first, vertices are processed in the same order they were discovered. This order is what makes the search move outward evenly from the source.
The Algorithm in Steps
- Put the source in the visited set and in the queue.
- While the queue is not empty:
- Remove the vertex at the front of the queue. Call it
node. - Process
node. In this chapter, processing means appending it to an output list. - For each neighbor of
node: if the neighbor is not in the visited set, add it to the set and append it to the back of the queue. - When the queue is empty, every vertex reachable from the source has been processed exactly once.
The Reference Implementation
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']Here is what each part does:
visited = {start}marks the source before the loop begins. If you skip this, a cycle back to the source would enqueue it a second time.queue.popleft()takes from the front of the queue andqueue.appendadds to the back. This pairing is what makes the queue FIFO. On adeque, both operations run in O(1).- The neighbor is added to
visitedas soon as it is discovered, before it is dequeued. The next chapter explains why this timing matters. For now, the effect to remember is that each vertex enters the queue at most once.
Tracing the Example
The graph above is directed and contains no cycles. Vertex D can be reached through both B and C, and F through both D and E. These shared vertices are where the visited check does its work.
| Step | Dequeued | Neighbors examined | Newly enqueued | Queue after step | Visited after step |
|---|---|---|---|---|---|
| init | none | none | A | [A] | {A} |
| 1 | A | B, C | B, C | [B, C] | {A, B, C} |
| 2 | B | D | D | [C, D] | {A, B, C, D} |
| 3 | C | D, E | E (D skipped) | [D, E] | {A, B, C, D, E} |
| 4 | D | F | F | [E, F] | {A, B, C, D, E, F} |
| 5 | E | F | none (F skipped) | [F] | unchanged |
| 6 | F | none | none | [] | unchanged |
The output order is A, B, C, D, E, F. A is at distance 0 from the source. B and C are at distance 1, D and E at distance 2, and F at distance 3. The output lists them in that order: all of one distance before any of the next. A later chapter proves that this holds for every graph. For now, notice that the queue never holds vertices from more than two adjacent distances at once.
What the Order Depends On
BFS fixes the order of distance levels. It does not fix the order of vertices inside a level. Within a level, the order comes from the order of each adjacency list and the order in which their owners were dequeued. If A's list were ['C', 'B'], the output would be A, C, B, D, E, F. That is still a valid BFS order.
Edge Cases the Basic Version Handles
Disconnected graphs. BFS visits only vertices reachable from the source. Add an isolated vertex 'G': [] to the graph and bfs(graph, 'A') still returns six vertices. A later chapter on connected components covers how to reach every vertex.
Directed reachability. Edges are followed in their stored direction only. bfs(graph, 'D') returns ['D', 'F']. A is not reached even though A can reach D.
Cycles and self-loops. The visited check stops the search from going around a cycle forever. A self-loop such as 'X': ['X'] is harmless because X is already in visited when its own list is scanned.
Undirected graphs. An undirected edge must appear in both adjacency lists. If you store {0: [1], 1: []} and start from 1, you will never reach 0.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `list.pop(0)` instead of `deque.popleft()` | Correct output, but each pop costs O(n), so large graphs run in quadratic time | Use `collections.deque` |
| `queue.pop()` on a deque or list | The container acts as a stack, so the order is no longer breadth-first | Use `popleft()` |
| Source not added to `visited` at the start | The source is processed twice when an edge leads back to it | Initialize `visited = {start}` |
| Checking visited only at dequeue time | The same vertex sits in the queue many times, which wastes time and memory | Mark when enqueuing (next chapter) |
| A neighbor that is not a key in `graph` | `KeyError` when that neighbor is dequeued | Make every vertex a key, or use `graph.get(node, ())` |
| Using a `list` for `visited` | `in` checks cost O(n) | Use a `set` |
When the input might be loosely built, for example edges parsed from a file where sink vertices have no entry of their own, a defensive version avoids the KeyError:
from collections import deque
def bfs_safe(graph, start):
visited = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph.get(node, ()):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
edges = [('A', 'B'), ('A', 'C'), ('C', 'D')]
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
print(bfs_safe(graph, 'A')) # ['A', 'B', 'C', 'D']In this graph, B and D are never keys. graph.get treats a missing vertex as one with no outgoing edges.
Where "Process" Fits
In the reference code, processing a vertex means appending it to order. Real uses replace that line with whatever the problem needs: testing whether the vertex is the goal, recording its distance, or counting vertices. The skeleton around that line stays the same. Every later chapter in this tutorial keeps this loop unchanged and changes only three things: what is stored per vertex, what happens at dequeue time, and how the queue is seeded.
Exercises
Exercise
Run bfs on the chapter's graph, but change A's adjacency list to ['C', 'B']. What order is returned, and why is it still a valid BFS order?
Show answer
['A', 'C', 'B', 'D', 'E', 'F']. When A is dequeued, it enqueues C and then B. When C is dequeued, it enqueues D and E. When B is dequeued, D is already visited. Then D enqueues F, and E finds F already visited. The order inside distance 1 (C before B) changed, but every distance-1 vertex still comes before every distance-2 vertex, and F at distance 3 comes last.
Exercise
Someone replaces queue.popleft() with queue.pop() in the reference code and keeps everything else the same. What order does the call on the original graph return, and which BFS property is lost?
Show answer
['A', 'C', 'E', 'F', 'D', 'B']. The container now acts as a stack. After A is processed, it holds [B, C], and C is popped first. C pushes D and E, then E is popped and pushes F. F is processed, then D (its neighbor F is already visited), then B. B is at distance 1 but is output after F, which is at distance 3. The guarantee that vertices come out in order of nondecreasing distance from the source is lost.
Exercise
For the undirected graph {1: [2], 2: [1, 3], 3: [2], 4: [5], 5: [4]}, what does bfs(graph, 3) return, and why are 4 and 5 missing?
Show answer
[3, 2, 1]. Starting at 3, BFS reaches 2 and then 1. Vertices 4 and 5 form a separate connected component with no edge to {1, 2, 3}, so the search can never reach them from 3.