Multi-source and 0-1 BFS on grids
About this lesson
A grid of cells is a graph, and breadth-first search finds the fewest moves across it. Two small changes make BFS much more useful. Start it from every source at once and one pass gives each cell its distance to the nearest source. Let moves cost 0 or 1 and a deque, with free moves pushed to the front, finds the cheapest routes without a heap. The Software lessons "Graphs" and "Graph search: BFS and DFS" cover graphs, queues and plain BFS; this lesson builds on them.
A grid is a graph
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.
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)
Read the lesson step by step
A grid is a graph
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.
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)Distance to the nearest source
Now there are two sources, A and B, like two exits. For every cell we want the moves to the NEAREST one. Running BFS from A, then again from B, and keeping the smaller answer works, but costs two full passes.
sources: A = (0,0), B = (3,4) want: dist(cell) = min(moves from A, moves from B) one BFS per source: k sources → k passes, O(k·(V + E))Every source starts in the queue
Multi-source BFS does it in one pass. Before the loop, put every source in the queue and give each distance 0. A queue is first in, first out: append adds at the back, popleft takes from the front.
q = deque(sources) # [(0,0), (3,4)] for s in sources: dist[s] = 0 append((0,0)) d=0 append((3,4)) d=0Both waves take one step
Pop A from the front: its two new neighbours get distance 1 and join the back. Pop B: the same. The queue now holds only 1s, so every cell one move from either source is handled before any cell two moves away.
pop a cell, label each unlabelled neighbour dist + 1, append it popleft((0,0)) d=0 append((1,0)) d=1 append((0,1)) d=1 popleft((3,4)) d=0 append((2,4)) d=1 append((3,3)) d=1The waves spread
Popping the 1s labels the 2s. A neighbour that already has a number is skipped, so no cell is labelled twice. When the A wave and the B wave touch, a cell keeps the first number it gets: the one from the nearer source.
if u not in dist: a labelled cell is never relabelled popleft((1,0)) d=1 append((2,0)) d=2 append((1,1)) d=2 popleft((0,1)) d=1 append((0,2)) d=2 popleft((2,4)) d=1 append((1,4)) d=2 append((2,3)) d=2 popleft((3,3)) d=1 append((3,2)) d=2One pass, nearest distances
The queue empties. Every cell holds its moves to the nearest source, at most 3 here. Each of the 20 cells went in and out of the queue once, so the cost is O(V + E), the same as one BFS.
dist to the nearest source: 0 1 2 3 3 1 2 3 3 2 2 3 3 2 1 3 3 2 1 0 appends: 20 pops: 20 longest queue: 8 same as one BFS from an extra start joined to A and BMoves that cost 0 or 1
New question. Walls rise; you may break through one for a cost of 1. Stepping onto an open cell costs 0. What is the fewest walls to break from A to each cell? Plain BFS counts moves, not walls, so it gives wrong answers.
map (# = wall): A.#.. ..#.. ##.## ...#B cost of a move = 1 onto a wall, 0 onto an open cell edge weights are only 0 or 1Free moves go to the front
Use a deque, a queue you can add to at both ends. Pop A. Its open neighbours cost 0 more, so appendleft puts them at the FRONT, ahead of everything. A move onto a wall costs 1, so append puts it at the back.
dist[A] = 0, q = deque([A]) append((0,0)) d=0 popleft((0,0)) d=0 appendleft((1,0)) d=0 appendleft((0,1)) d=0 w = 0 → appendleft (front) w = 1 → append (back)The deque stays in order
Keep popping the front. The deque only ever holds two values, d at the front and d + 1 behind, so cells come out in order of walls broken: every 0, then every 1, then every 2, B among them.
deque holds values d … d, d+1 … d+1 pop order of d: 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 appends: 20 pops: 20 longest deque: 6Two walls from A to B
Done: B shows 2, so the best route from A to B breaks 2 walls. Like plain BFS, 0-1 BFS runs in O(V + E) time, with no heap like Dijkstra's algorithm needs.
fewest walls to break from A: 0 0 1 1 1 0 0 1 1 1 1 1 1 2 2 1 1 1 2 2 B = (3,4): 2 Dijkstra with a binary heap: O((V + E) log V) 0-1 BFS with a deque: O(V + E)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01In multi-source BFS with sources A and B, what goes in the queue before the loop starts?
Every source starts in the queue at distance 0. The queue then hands out all the 0s, then all the 1s, and so on, so each cell's first label is its distance to the nearest source.
02On a grid with V cells, you have k sources. How does one multi-source BFS compare with running a separate BFS from each source?
Multi-source BFS labels each cell once, exactly like a single BFS. Running BFS from every source repeats the whole search k times.
03In 0-1 BFS, a move onto an open cell costs 0. Where does that cell go in the deque?
A 0-cost move gives the same distance as the cell just popped, which is the smallest in the deque, so it belongs at the front. A 1-cost move gives d + 1, the largest, so it goes at the back.
04Why does plain BFS give the wrong answer for "fewest walls to break"?
BFS orders cells by number of moves. A long walk through open cells can break fewer walls than a short one through walls, so the order by moves is not the order by cost.
05Edges can cost 0, 1 or 5. Which algorithm should you use?
The deque trick relies on every distance in it being d or d + 1. With a weight of 5 that breaks. Dijkstra's algorithm handles any weights that are not negative.
Glossary
- Grid graph
- A graph whose nodes are the cells of a grid, each joined to the cells directly up, down, left and right of it.
- Breadth-first search (BFS)
- A search that visits nodes in order of their number of moves from the start, using a first-in, first-out queue.
- Multi-source BFS
- BFS that starts with every source in the queue at distance 0, giving each node its distance to the nearest source in one pass.
- Deque
- A double-ended queue: you can add and remove items at both ends. In Python, collections.deque.
- 0-1 BFS
- A shortest-path search for edges that cost 0 or 1: 0-cost moves go to the front of a deque, 1-cost moves to the back.
- Edge weight
- The cost of moving along an edge. Plain BFS assumes every weight is 1.
- O(V + E)
- Time that grows with the number of nodes V plus the number of edges E: each is handled a constant number of times.
Notes and sources
- Multi-source BFS gives the same distances as one BFS from an imaginary extra start joined to every source by a free edge. Sedgewick and Wayne's BreadthFirstPaths has a constructor that takes several sources for exactly this.
- 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.
- 0-1 BFS is Dijkstra's algorithm for weights 0 and 1, with the deque doing the heap's job. With larger weights the trick breaks: use Dijkstra's algorithm with a priority queue.
- The code is real Python 3. collections.deque appends and pops at either end in about O(1); a list's pop(0) costs O(n). The full program prints both grids of this lesson.
- Sedgewick and Wayne, Algorithms 4th ed., BreadthFirstPaths.java (multiple-source constructor)
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 9: Breadth-First Search
- cp-algorithms: 0-1 BFS
- Python documentation: collections.deque
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), section 20.2 Breadth-first search
Quiz Unlocks after the last step.