Graphs · Pattern 6 of 14
Multi-source BFS: spread from many starts at once
Put every starting cell in the queue before the first step. The BFS then spreads from all of them together, and each cell is reached first by its nearest source.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Something spreads from several places at the same time (rot, fire, water)
- The distance from each cell to its nearest source
- Searching from every source one by one would be too slow
The template
int orangesRotting(int[][] grid) {
int m = grid.length, n = grid[0].length, fresh = 0;
Deque<int[]> q = new ArrayDeque<>();
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++) {
if (grid[r][c] == 2) q.offer(new int[]{r, c}); // every source starts in the queue
else if (grid[r][c] == 1) fresh++;
}
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int minutes = 0;
while (!q.isEmpty() && fresh > 0) {
for (int size = q.size(); size > 0; size--) { // one minute
int[] cur = q.poll();
for (int[] d : dirs) {
int r = cur[0] + d[0], c = cur[1] + d[1];
if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] == 1) {
grid[r][c] = 2; fresh--;
q.offer(new int[]{r, c});
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
} from collections import deque
def oranges_rotting(grid):
m, n = len(grid), len(grid[0])
q, fresh = deque(), 0
for r in range(m):
for c in range(n):
if grid[r][c] == 2:
q.append((r, c)) # every source starts in the queue
elif grid[r][c] == 1:
fresh += 1
minutes = 0
while q and fresh:
for _ in range(len(q)): # one minute
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
q.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1 int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), fresh = 0;
queue<pair<int, int>> q;
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++) {
if (grid[r][c] == 2) q.push({r, c}); // every source starts in the queue
else if (grid[r][c] == 1) fresh++;
}
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int minutes = 0;
while (!q.empty() && fresh > 0) {
for (int size = q.size(); size > 0; size--) { // one minute
auto [r, c] = q.front(); q.pop();
for (auto& d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nc >= 0 && nr < m && nc < n && grid[nr][nc] == 1) {
grid[nr][nc] = 2; fresh--;
q.push({nr, nc});
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
} function orangesRotting(grid) {
const m = grid.length, n = grid[0].length;
let q = [], fresh = 0;
for (let r = 0; r < m; r++)
for (let c = 0; c < n; c++) {
if (grid[r][c] === 2) q.push([r, c]); // every source starts in the queue
else if (grid[r][c] === 1) fresh++;
}
let minutes = 0;
while (q.length && fresh > 0) {
const next = []; // what rots in the next minute
for (const [r, c] of q)
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]])
if (nr >= 0 && nc >= 0 && nr < m && nc < n && grid[nr][nc] === 1) {
grid[nr][nc] = 2; fresh--;
next.push([nr, nc]);
}
q = next;
minutes++;
}
return fresh === 0 ? minutes : -1;
} The variations
-
1Spread from every source at once
Queue all rotten oranges, gates or fires first, then BFS level by level: each level is one minute. To escape a fire, first record when the fire reaches each cell, then check that you get there strictly sooner.
Now you solve -
2Distance to the nearest source
Start from every 0, every thief or one whole island, and the first time BFS reaches a cell is its distance to the nearest one. For the safest path, compute those distances first, then find the path that keeps the smallest one as large as possible.
Now you solve -
3Search backwards from the goal
Instead of asking where water from each cell can go, start from each ocean and climb uphill. The cells reached from both oceans are the answer: two searches instead of one per cell.
-
4One BFS per source, then combine
When you need the total distance to every source (every building), run a BFS from each one and add its distances into a shared grid, with a count of how many reached each cell. Only cells reached by all of them count.
Mistakes to avoid
- Counting a minute for the last level even though it rotted nothing: stop once nothing is fresh, or the answer is one too big.
- Running a separate BFS from every source: that is O(k·m·n). One queue with all sources is O(m·n).
- Forgetting the case with no fresh oranges at all: the answer is 0, not −1.
Lesson done
Next: Cycle detection and bipartite graphs →Mark it done once you can write the template from memory and you have solved the worked examples yourself.