Breadth-first search (BFS)
Breadth-first search (BFS) walks out from the start ring by ring, with a deque as the queue and a seen set marked when a vertex is enqueued, so the first time it reaches a vertex is by the fewest steps.
"How many people stand between you and a stranger", "the fewest moves from the entrance of a maze to its exit", "the fewest stops from this metro station to that one": all ask for the fewest steps. The way to answer is to start at the start, find everything one step away, then everything one step from those, spreading out ring by ring; the first time the target is reached, the steps taken are the fewest. That is breadth-first search (BFS). It needs one queue and one set, a dozen lines of code; but put one line in the wrong place (when a vertex gets marked "seen") and a 20 × 20 grid enqueues 361 extra times, and a larger graph grinds to a halt.
Spreading out ring by ring
BFS uses a queue: first in is first out, so whatever is closer to the start is always handled first. A set seen records "vertices already found", so the walk never goes round a cycle forever.
- Put the start in
seenand in the queue. - While the queue is not empty: take u from the front and look at each neighbour v of u; if v has not been seen, mark it and put it at the back.
Queue
1from collections import deque2 3graph = {4 "A": ["B", "C"],5 "B": ["A", "D"],6 "C": ["A", "D", "E"],7 "D": ["B", "C", "F"],8 "E": ["C", "F"],9 "F": ["D", "E"],10}11 12def bfs(graph, start):13 seen = {start}14 q = deque([start])15 order = []16 while q:17 u = q.popleft()18 order.append(u)19 for v in graph[u]:20 if v not in seen:21 seen.add(v) # marked the moment it is enqueued22 q.append(v)23 return order24 25print(bfs(graph, "A"))26print(bfs(graph, "F"))
['A', 'B', 'C', 'D', 'E', 'F'] ['F', 'D', 'E', 'B', 'C', 'A']
Every vertex is enqueued and dequeued once, and every edge is looked at once from each end: time O(n + e); the queue and seen hold at most n items, space O(n).
Always use collections.deque for the queue: popleft() is O(1). A list's pop(0) shifts every item behind it each time (chapter 2, "queues"), which makes BFS O(n²).
Note that 1's neighbours are stored as [3, 2]. What does it print?
1from collections import deque2 3graph = {1: [3, 2], 2: [4], 3: [4, 5], 4: [6], 5: [6], 6: []}4seen = {1}5q = deque([1])6order = []7while q:8 u = q.popleft()9 order.append(u)10 for v in graph[u]:11 if v not in seen:12 seen.add(v)13 q.append(v)14print(order)
[1, 3, 4, 6, 5, 2] is the go-all-the-way-down order of DFS (the next lesson). 6 is enqueued only once, because it is marked when it joins.An undirected graph has the edges A–C, A–E, C–B, C–D, E–F, B–F, and neighbours are looked at in alphabetical order. In what order does BFS from A visit the vertices?
A graph with n vertices is stored as an adjacency matrix. How long does BFS take?
Mark when you enqueue
A very common way to write it marks a vertex as seen only when it is dequeued. The result looks just as right, but the same vertex joins the queue several times: D is a neighbour of both B and C; when B leaves, D is not marked yet and joins once; when C leaves, D is still waiting in the queue, still unmarked, and joins again.
if v not in seen: seen.add(v); q.append(v)6 vertices, 6 enqueuesits place is taken before it joins, so nobody adds it againu = q.popleft(); if u in seen: continue; seen.add(u)6 vertices, 8 enqueuesD and F join twice each; the extra copies are skipped when they leaveCount the enqueues of both versions, on the graph and on a 20 × 20 grid (each cell joined to the ones above, below, left and right):
1from collections import deque2 3def bfs_early(graph, start):4 seen = {start}5 q = deque([start])6 pushes = 17 while q:8 u = q.popleft()9 for v in graph[u]:10 if v not in seen:11 seen.add(v) # marked when enqueued12 q.append(v)13 pushes += 114 return pushes15 16def bfs_late(graph, start):17 seen = set()18 q = deque([start])19 pushes = 120 while q:21 u = q.popleft()22 if u in seen: # marked only when dequeued23 continue24 seen.add(u)25 for v in graph[u]:26 if v not in seen:27 q.append(v)28 pushes += 129 return pushes30 31graph = {32 "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],33 "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"],34}35print("6 vertices:", bfs_early(graph, "A"), "enqueues versus", bfs_late(graph, "A"))36 37k = 2038grid = {}39for r in range(k):40 for c in range(k):41 grid[(r, c)] = [(r + dr, c + dc) for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1))42 if 0 <= r + dr < k and 0 <= c + dc < k]43print("20 × 20 grid:", bfs_early(grid, (0, 0)), "enqueues versus", bfs_late(grid, (0, 0)))
6 vertices: 6 enqueues versus 8 20 × 20 grid: 400 enqueues versus 761
On the grid's 400 cells, marking when dequeued enqueued 761 times, nearly double, and the queue grows with it. Forget the if u in seen: continue as well, and each repeated cell adds its neighbours all over again when it leaves, so the count multiplies further. Remember one rule: mark a vertex the moment it goes into the queue.
1's two neighbours, 2 and 3, are both joined to 4. This time vertices are marked when they leave the queue. pops records each vertex popped. What does this print?
1from collections import deque2 3graph = {1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3]}4seen = set()5q = deque([1])6pops = []7while q:8 u = q.popleft()9 pops.append(u)10 if u in seen:11 continue12 seen.add(u)13 for v in graph[u]:14 if v not in seen:15 q.append(v)16print(pops)
Fewest steps and the path
BFS dequeues layer by layer: the first time v is found, it is by the fewest edges (every vertex reachable in fewer steps sits ahead in the queue and was handled first). So swap seen for a dict dist: dist[v] = dist[u] + 1, which doubles as the record of what has been seen.
To know the way, also record prev[v] = u: v was found from u. Walk back from the end along prev until the start, reverse it, and that is a shortest path.
1from collections import deque2 3graph = {4 "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],5 "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"],6 "G": [],7}8 9def shortest(graph, start):10 dist = {start: 0}11 prev = {start: None}12 q = deque([start])13 while q:14 u = q.popleft()15 for v in graph[u]:16 if v not in dist: # dist doubles as seen17 dist[v] = dist[u] + 118 prev[v] = u19 q.append(v)20 return dist, prev21 22def path_to(prev, end):23 path = []24 while end is not None:25 path.append(end)26 end = prev[end]27 return path[::-1]28 29dist, prev = shortest(graph, "A")30print(dist)31print("A to F:", dist["F"], "steps, route", path_to(prev, "F"))32print("A to G:", dist.get("G", -1))
{'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}
A to F: 3 steps, route ['A', 'B', 'D', 'F']
A to G: -1
G is not joined to anything, so BFS never reaches it and it is not in dist; dist.get("G", -1) says "can't get there".
BFS's "fewest" only holds when every edge counts as 1 step. When edges carry different weights (kilometres, minutes), the path with the fewest edges is not always the shortest: that takes Dijkstra, lesson 5.
When is the dist BFS gives a vertex, the first time it sees it, sure to be the shortest path to it?
An undirected graph has the edges A–C, A–E, C–B, C–D, E–F, B–F. BFS starts from A. What is dist[F]?
The fewest steps
✓Complete steps(graph, start, end): graph is an undirected adjacency list (a dict). Return the fewest edges from start to end, or -1 if end can't be reached. When start and end are the same, return 0.
3 2 0 -1
1from collections import deque2 3def steps(graph, start, end):4 # dist doubles as seen; when end is dequeued, return its distance5 return -16 7graph = {8 1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3, 5],9 5: [4], 6: [7], 7: [6],10}11print(steps(graph, 1, 5), steps(graph, 2, 3), steps(graph, 1, 1), steps(graph, 1, 7))
A grid maze
A grid problem needs no graph built first: the neighbours of a cell (r, c) are the four cells above, below, left and right; work them out, check they are inside the grid and not a wall, and each one is an edge. Write the four directions as one tuple, ((-1, 0), (1, 0), (0, -1), (0, 1)), and one loop covers them.
1from collections import deque2 3maze = [4 "S..#.",5 "##.#.",6 ".....",7 ".###E",8]9 10def maze_steps(maze):11 rows, cols = len(maze), len(maze[0])12 for r in range(rows):13 for c in range(cols):14 if maze[r][c] == "S":15 start = (r, c)16 elif maze[r][c] == "E":17 end = (r, c)18 dist = {start: 0}19 q = deque([start])20 while q:21 r, c = q.popleft()22 if (r, c) == end:23 return dist[(r, c)] # the first time it leaves is the fewest steps24 for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):25 nr, nc = r + dr, c + dc26 if 0 <= nr < rows and 0 <= nc < cols and maze[nr][nc] != "#" and (nr, nc) not in dist:27 dist[(nr, nc)] = dist[(r, c)] + 128 q.append((nr, nc))29 return -1 # unreachable30 31print(maze_steps(maze))32print(maze_steps(["S#E"]))
7 -1
The order inside the condition matters: 0 <= nr < rows comes before maze[nr][nc]. and works left to right, so outside the grid it never goes on to read maze[-1] (Python's negative indexes don't raise an error; they quietly read the last row, and that kind of bug is the hardest to find).
| Time | Extra space | Notes | |
|---|---|---|---|
| BFS on adjacency lists | O(n + e) | O(n) | every vertex in and out of the queue once, every edge looked at twice |
| BFS on an R × C grid | O(R × C) | O(R × C) | at most 4 neighbours per cell |
| list.pop(0) as the queue | O(n²) and up | O(n) | every dequeue shifts the whole queue |
| Marking when dequeued | enqueues can double | a longer queue | the same vertex joins several times |
In interviews: "fewest steps", "fewest changes", "nearest", with every step costing the same: think BFS first. While writing it, say three things: a deque, marking on enqueue, dist doubling as seen. For a grid, write the four directions as a tuple and put the bounds check before reading the cell.
The bounds check is forgotten, and the cells in four directions from (0, 0) are read. What does this print?
1maze = ["S.", "#E"]2r, c = 0, 03cells = ""4for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):5 nr, nc = r + dr, c + dc6 cells += maze[nr][nc]7print(cells)
maze[-1][0]; a negative index raises no error and reads the last row's #. Down: maze[1][0] is #. Left: maze[0][-1] reads the last cell of row 0, a dot. Right: maze[0][1] is a dot. Not a single error, and all four are cells from somewhere else: that's why 0 <= nr < rows comes before reading the cell.A grid maze with R rows and C columns, searched with this step's BFS. How long does it take at worst?
How you write it at work
The standard library has no ready-made BFS (third-party libraries like networkx do), so at work you write these dozen lines yourself, all with the standard library:
collections.deque:appendto join,popleftto leave, both O(1).distis a dict, and its keys can be anything hashable: strings,(r, c)tuples, even a whole state tuple.- Once the target is found,
return: there is no need to walk the whole graph. - To handle one layer at a time ("how many in layer k"), note
len(q)at the start of each round and pop exactly that many: what comes out is one whole layer.
1from collections import deque2 3graph = {"me": ["Ann", "Bea"], "Ann": ["me", "Cal"], "Bea": ["me", "Cal", "Dee"],4 "Cal": ["Ann", "Bea", "Ed"], "Dee": ["Bea"], "Ed": ["Cal"]}5 6seen = {"me"}7q = deque(["me"])8level = 09while q:10 this_level = []11 for _ in range(len(q)): # pop only this layer's count12 u = q.popleft()13 this_level.append(u)14 for v in graph[u]:15 if v not in seen:16 seen.add(v)17 q.append(v)18 print(f"layer {level}:", this_level)19 level += 1
layer 0: ['me'] layer 1: ['Ann', 'Bea'] layer 2: ['Cal', 'Dee'] layer 3: ['Ed']
range(len(q)) is worked out when the loop starts, so the next layer added to q during the loop is not popped in this round.
Group by layer
✓Complete levels(graph, start): return a list whose item k holds every vertex exactly k steps from start (in the order they leave the queue).
[['A'], ['B', 'C'], ['D', 'E'], ['F']] [['E'], ['C', 'F'], ['A', 'D'], ['B']]
1from collections import deque2 3def levels(graph, start):4 result = []5 # each round, note len(q) first and pop exactly that many: that is one whole layer6 return result7 8graph = {9 "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],10 "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"],11}12print(levels(graph, "A"))13print(levels(graph, "E"))
Summary
BFS: spreading out ring by ring
- The queue is a deque: append to join, popleft to leave, O(1)
- Mark seen the moment a vertex is enqueued; marking when dequeued enqueues it again and again
- The layer where v is first found is the fewest steps: dist[v] = dist[u] + 1, prev rebuilds the path
- A grid cell's neighbours are the four around it: check the bounds before reading the cell
- Time O(n + e); shortest only when every step costs the same
1seen = {start}; q = deque([start])2while q:3 u = q.popleft()4 for v in graph[u]:5 if v not in seen:6 seen.add(v); q.append(v)