A012301230123012301230123012301231q = deque(sources)2for s in sources: dist[s] = 03while q:4 v = q.popleft()5 for u in nbrs(v):6 if u not in dist:7 dist[u] = dist[v] + 18 q.append(u)1while q:2 v = q.popleft()3 for u in nbrs(v):4 w = cost[u]5 if dist[v] + w < dist[u]:6 dist[u] = dist[v] + w7 if w: q.append(u)8 else: q.appendleft(u)01230123012301230123012301230123012301230123B0123frontback0011112222223333333300001111111122111212
Tiles: one node each; the number is its distanceTray: the deque, front on the left, back on the rightA hopping token: one tile added to or taken from the dequeEvery deque operation of the real Python program, replayed: a token hops from a tile into the tray when the tile is added and back to its tile when it is taken from the front. With A and B both in the queue at 0, one pass labels each tile with its moves to the nearer source. With walls costing 1 and open tiles 0, free moves go to the front of the deque and walls to the back, so tiles come out in order of walls broken.

Grids are graphs

  1. Each square cell is a node. Its neighbours are the cells directly up, down, left and right: those are its edges. Every move costs 1, so breadth-first search (BFS) finds the fewest moves from a start cell.

Many sources at once

Moves that cost 0 or 1

What happens

;; step 1/10 · grid-graph
grid: 4 rows × 5 columns = 20 cells (nodes)
neighbours of (r, c): (r-1, c) (r+1, c) (r, c-1) (r, c+1)
edges: 4·4 across + 3·5 down = 31 neighbour pairs

BFS on a graph with V nodes and E edges: O(V + E)

BFS is correct because the queue hands out cells in order of distance: all the 0s, then all the 1s, then all the 2s. Starting with every source at 0 keeps that order, so the first label a cell gets is its distance to the nearest source. In 0-1 BFS a cell can be put in the deque more than once if a cheaper route turns up later. The old copy is harmless: when it is popped, no neighbour improves. Popping a cell, then, never lowers a distance that is already final.