Video in progress
When several sources spread at the same time on a grid (for example rotting oranges), how do you compute the time to reach each cell?
Multi-source BFS: we put all the sources into the queue at the start with distance 0 and run an ordinary BFS. Each cell is marked in the first wave that arrives from its nearest source. O(R·C), whereas a separate BFS from each source would be O(k·R·C).
📖 Answer
Running a separate BFS from each source and taking the minimum is also correct, but slow when there are many sources. BFS spreads layer by layer like a wave, so starting everything at once is enough.
static int minutesToRot(int[][] grid) {
int rows = grid.length, cols = grid[0].length, fresh = 0;
Deque<int[]> q = new ArrayDeque<>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) q.add(new int[]{r, c});
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 layer = one minute
int[] cell = q.poll();
for (int[] d : dirs) {
int nr = cell[0] + d[0], nc = cell[1] + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != 1) continue;
grid[nr][nc] = 2; // we mark when adding to the queue, not when taking out
fresh--;
q.add(new int[]{nr, nc});
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
The most common mistake is marking a cell when you take it out of the queue. Then the same cell gets into the queue repeatedly from several neighbors, and the queue blows up.
Tell the interviewer that we're modifying the input array. In library code I wouldn't do that; I'd use a separate boolean[][] visited or int[][] dist.
The same idea exists in practice too: the distance from each house to the nearest shop on a map, or the propagation time of a message in a network. If the edge weights differ, instead of BFS you need Dijkstra started from all the sources.
Sign up to mark studied questions and save your progress.