Sub topic 12
Multi-Source BFS
This chapter assumes you already know standard BFS with a deque, why marking vertices when they are enqueued prevents duplicates, and how BFS on a grid treats each open cell as a vertex. Here you will learn how to find each vertex's distance to the nearest of several starting points in a single BFS.
The problem
Many questions have more than one origin. Some examples:
- How far is every house from the nearest fire station?
- How many minutes until rot spreads from all the rotten oranges to the rest of the crate?
- For each open cell in a maze, how far away is the closest exit?
One obvious approach runs a separate BFS from each of the k sources and keeps the minimum distance for each vertex. That costs O(k · (V + E)). Multi-source BFS gets the same answer in O(V + E).
The idea: start with every source in the queue
Standard BFS puts one vertex at distance 0 into the queue. Multi-source BFS puts all sources into the queue at distance 0, marks them all visited, and then runs the usual loop with no other changes.
To see why this works, imagine adding a virtual "super-source" vertex with an edge to every real source. A normal BFS from the super-source reaches all real sources in layer 1. After that, each vertex's layer equals 1 plus its distance to the nearest real source. Seeding the queue with all the sources is the same as starting that BFS one step in, after layer 1, so the distances come out without the extra 1.
The FIFO order still guarantees that every vertex at distance d leaves the queue before any vertex at distance d + 1. So the first time a vertex is discovered, it is discovered from its nearest source.
Worked example on a grid
In this grid, S marks a source, . is open, and # is a wall. The function returns each cell's distance to the nearest source, or -1 for walls and unreachable cells.
from collections import deque
def nearest_source(grid):
rows, cols = len(grid), len(grid[0])
dist = [[-1] * cols for _ in range(rows)]
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 'S':
dist[r][c] = 0
queue.append((r, c))
while queue:
r, c = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if (0 <= nr < rows and 0 <= nc < cols
and grid[nr][nc] != '#' and dist[nr][nc] == -1):
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return dist
grid = ['S..',
'.#.',
'..S']
print(nearest_source(grid)) # [[0, 1, 2], [1, -1, 1], [2, 1, 0]]The two waves grow at the same speed. Cell (0, 2) is two steps from each source, and the wave that reaches it first claims it. Since both waves arrive at the same distance, the distance is correct either way.
If you also need to know which source is nearest, keep an owner array. Set owner for each source to the source itself, and when a neighbor is discovered, copy the owner of the cell that discovered it. If two sources are equally close, the one whose wave reaches the cell first wins the tie.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Running one BFS per source | O(k · (V + E)) time | Seed one queue with all sources |
| Not marking sources visited before the loop | A source can be re-discovered and given distance 1 or more | Set `dist = 0` for every source when you enqueue it |
| Starting BFS from one source, then adding the others later | Layers mix, so distances are wrong | Enqueue all sources before the first `popleft` |
| Using a stack instead of a queue | Order is no longer by distance | Use `deque` with `append` and `popleft` |
Exercise
Using nearest_source, what does the 1×5 grid ['S...S'] produce, and how many times is each cell enqueued?
Show answer
[[0, 1, 2, 1, 0]]. Each cell is enqueued exactly once, because a cell is marked with a distance as soon as it is enqueued and is never enqueued again.
Exercise
A city graph has 10,000 intersections, 30,000 roads, and 200 fire stations. About how much work does running one BFS per station take, compared with a single multi-source BFS?
Show answer
Running one BFS per station costs about 200 × (10,000 + 30,000) = 8,000,000 steps. A single multi-source BFS costs about 40,000 steps, roughly 200 times less, and gives the same nearest-station distances.