Sub topic 12
Multi-Source BFS
This chapter assumes you already know how single-source BFS works. That means a FIFO queue, marking vertices visited when they are enqueued, and the fact that BFS settles vertices in order of nondecreasing distance. It also assumes you have seen BFS on grids. Here we change one thing: the search starts from several vertices at once.
The Problem It Solves
Many questions ask for the distance to the nearest member of a set. Some examples:
- In a city map, how far is each intersection from the closest fire station?
- In a grid, how many steps separate each open cell from the nearest wall or exit?
- Rot or fire spreads from several starting cells at once. How many minutes until it reaches everything?
The obvious approach runs one BFS per source and keeps the minimum distance at each vertex. With k sources this costs O(k(V + E)). Multi-source BFS gets the same answer in a single O(V + E) pass.
The Idea: Start With Every Source in Layer 0
Put all sources in the queue before the loop starts. Give each of them distance 0 and mark each one visited. Then run the ordinary BFS loop with no other changes.
The queue now begins with a whole layer 0 instead of a single vertex. Everything BFS guarantees still holds. Layer 1 is every unvisited vertex adjacent to any source. Layer 2 is every unvisited vertex adjacent to layer 1, and so on. A vertex lands in layer d exactly when its nearest source is d edges away.
Why it is correct: the virtual super-source
Imagine adding one extra vertex S with an edge to every real source. Run single-source BFS from S. After S is dequeued, the queue holds exactly the real sources, all at distance 1 from S. From that point the run matches multi-source BFS step for step, with every distance shifted up by 1. Any shortest path from S to a vertex v passes through exactly one real source. So the BFS distance from S, minus 1, is the distance from v to its nearest source.
You never build S in code. Seeding the queue with all the sources does the same job.
Implementation on an Adjacency List
This version records two things for each vertex: its distance to the nearest source, and which source that is. The nearest dictionary is inherited down the BFS tree the same way dist is computed. Each vertex copies the label of the vertex that discovered it.
from collections import deque
def multi_source_bfs(graph, sources):
dist = {}
nearest = {}
queue = deque()
for s in sources:
if s not in dist: # ignore duplicate sources
dist[s] = 0
nearest[s] = s
queue.append(s)
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in dist:
dist[neighbor] = dist[node] + 1
nearest[neighbor] = nearest[node]
queue.append(neighbor)
return dist, nearest
# An undirected path 1-2-3-4-5-6-7 with sources at 1 and 6
graph = {
1: [2], 2: [1, 3], 3: [2, 4], 4: [3, 5],
5: [4, 6], 6: [5, 7], 7: [6],
}
dist, nearest = multi_source_bfs(graph, [1, 6])
print({v: dist[v] for v in sorted(dist)})
# {1: 0, 2: 1, 3: 2, 4: 2, 5: 1, 6: 0, 7: 1}
print({v: nearest[v] for v in sorted(nearest)})
# {1: 1, 2: 1, 3: 1, 4: 6, 5: 6, 6: 6, 7: 6}Vertices missing from dist cannot be reached from any source. The nearest labels split the graph into regions, one per source. This is the graph version of a Voronoi diagram.
Grid Example: Spreading From Several Cells
A standard exercise is the "rotting oranges" problem. In this grid, 2 is a rotten orange, 1 is a fresh one, and 0 is empty. Each minute, rot spreads to fresh oranges in the four neighboring cells. The function returns the minutes until no fresh orange is left, or -1 if some orange can never rot.
Every rotten cell starts spreading at minute 0, so every one of them is a source.
from collections import deque
def minutes_to_rot(grid):
grid = [row[:] for row in grid] # don't mutate the caller's grid
rows, cols = len(grid), len(grid[0])
queue = deque()
fresh = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c, 0))
elif grid[r][c] == 1:
fresh += 1
minutes = 0
while queue:
r, c, t = queue.popleft()
minutes = t # t never decreases in BFS order
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] == 1:
grid[nr][nc] = 2 # mark visited on enqueue
fresh -= 1
queue.append((nr, nc, t + 1))
return minutes if fresh == 0 else -1
print(minutes_to_rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]])) # 4
print(minutes_to_rot([[2, 1, 1], [0, 1, 1], [1, 0, 1]])) # -1
print(minutes_to_rot([[2, 1, 1, 1, 2]])) # 2The last test shows why all sources must start together. With two rotten ends, the middle orange rots at minute 2. A single source at either end would take 4 minutes.
Here the grid itself acts as the visited marker: changing a cell from 1 to 2 marks it. The final t dequeued is the largest distance, because BFS dequeues vertices in nondecreasing distance order.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Looping over sources and running a full BFS from each one with a shared visited set | The first source claims vertices that are closer to later sources, so distances come out too large | Enqueue every source before the loop starts |
| Enqueuing sources without marking them visited | Sources get rediscovered at distance 1 or 2, and distances are overwritten | Set `dist[s] = 0` (or mark the cell) as each source is enqueued |
| Not handling duplicate sources | A duplicate is processed twice. This is harmless for distances but wasted work, and it breaks per-source counting | Skip a source that is already in `dist` |
| Directed graph, asking for "distance to nearest target" | BFS over forward edges measures distance *from* the targets instead | Run multi-source BFS from the targets on the reversed graph |
| Expecting the distance to every source | Multi-source BFS keeps only the nearest one | Run separate BFS passes if you need all k distances, at O(k(V + E)) cost |
Edge Cases and Details
Ties between sources
A vertex can be equally far from two sources. The code above gives it the label of whichever equal-distance parent was dequeued first, and that depends on the order of the sources list. Distances are still correct; only the label is arbitrary. If ties matter, for example cells that should belong to no region, detect them by hand. When you scan an edge node -> neighbor where dist[neighbor] == dist[node] + 1 and nearest[neighbor] != nearest[node], the neighbor is contested.
Empty or unreachable cases
If sources is empty, the queue starts empty and nothing is reached. Decide what your caller expects in that case. In the orange problem, a grid with no fresh oranges returns 0 right away, which is correct. A grid with fresh oranges but no rotten ones returns -1.
Complexity
Each vertex is enqueued at most once, whether it is a source or not, and each adjacency list is scanned once. That gives O(V + E) time and O(V) extra space, no matter how many sources there are. The queue can start large: on a grid that is mostly sources, the initial queue is already O(V).
Relation to other variants
Multi-source seeding combines with the other BFS variants. You can seed a 0-1 BFS deque with several sources at distance 0. Bidirectional BFS also starts from two frontiers, but it differs from multi-source BFS. It keeps the two frontiers separate and stops when they meet, because it wants one path between two specific vertices. Multi-source BFS merges its sources into one frontier and computes distances to the whole set.
Exercise
A student writes for s in sources: bfs_from(s) with a single shared dist dictionary that is never reset, where each call skips vertices already in dist. On the path 1-2-3-4-5 with sources [1, 5], what distance does vertex 4 get, and what is the correct value?
Show answer
The BFS from 1 runs first and reaches every vertex, so vertex 4 gets distance 3. The BFS from 5 then finds everything already visited and changes nothing. The correct distance is 1, the length of the edge 5-4. The sources must be enqueued together so they expand at the same rate.
Exercise
In a directed road network, graph[u] lists the vertices reachable from u by one one-way street. You need, for every intersection, the number of streets to drive to the nearest hospital. Which graph do you run multi-source BFS on, and what are the sources?
Show answer
Build the reversed graph, with an edge v -> u for every original edge u -> v, and run multi-source BFS from all hospitals. A path from u to a hospital in the original graph is a path from that hospital to u in the reversed graph. BFS on the original edges would measure distance from the hospitals instead.
Exercise
Modify multi_source_bfs so that it also returns the set of vertices that are equally distant from two or more different sources. What check do you add, and where?
Show answer
Inside the neighbor loop, add an else branch for neighbors already in dist. If dist[neighbor] == dist[node] + 1 and nearest[neighbor] != nearest[node], add the neighbor to a contested set. Return contested alongside dist and nearest. A source is contested only if it appears twice, which the duplicate check already handles. Every equal-distance parent of a vertex is dequeued before that vertex is, so every competing parent gets a chance to scan the edge.