1. Multi-Source BFS with Level Snapshot
OptimalEnqueue all initially rotten oranges simultaneously at minute 0. Expand outwards level by level: each level represents 1 minute. Decrement fresh orange count until the queue empties.
Every cell in the M x N grid is visited at most once during the initial scan and at most once during the BFS queue operations.
The BFS queue can hold at most M x N orange coordinates in the worst case.
How It Works
Why DFS Fails for Simultaneous Spreading
In problems where multiple sources spread infection simultaneously (wildfires, virus contagion, rotting oranges), a standard DFS will trace one path deep to the end, recording incorrect time timestamps.
Instead, all rotten oranges spread their rot in parallel minute by minute. This is the definition of Multi-Source Breadth-First Search (BFS).
The Algorithm:
- Initial Scan:
- Count the total number of fresh oranges (
freshCount). - Collect the coordinates of all rotten oranges
'2'and push them into a FIFO queue. - If
freshCount == 0, return0immediately (no work needed).
- Level-by-Level Expansion:
- Initialize
minutesElapsed = 0. - While the queue is not empty and
freshCount > 0: - Record
levelSize = queue.size(). - For each node in the current level:
- Inspect all 4 neighbors: Up, Down, Left, Right.
- If a neighbor is a fresh orange (
grid[nr][nc] == 1): - Rot it:
grid[nr][nc] = 2. - Decrement
freshCount--. - Enqueue
(nr, nc). - After finishing all nodes in the level, increment
minutesElapsed++.
- Completion Check:
- If
freshCount == 0, returnminutesElapsed. - If
freshCount > 0, some fresh oranges were isolated and could never be reached; return-1.
Step-by-Step Dry Run
Rotten at (0, 0). Enqueue (0, 0). Total fresh oranges = 6. minutes = 0.
queue = [(0, 0)]fresh = 6- +Optimal O(m * n) runtime
- +Simulates simultaneous minute-by-minute wavefront expansion directly
- -Mutates input grid values in-place unless an auxiliary visited grid is used
Reference Implementation
Complete implementation for Multi-Source BFS with Level Snapshot in Python, JavaScript, Java, C++, and C.
from collections import dequedef oranges_rotting(grid: list[list[int]]) -> int:rows, cols = len(grid), len(grid[0])queue = deque()fresh = 0# Step 1: Scan gridfor r in range(rows):for c in range(cols):if grid[r][c] == 2:queue.append((r, c))elif grid[r][c] == 1:fresh += 1if fresh == 0:return 0minutes = 0directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]# Step 2: Multi-source BFSwhile queue and fresh > 0:for _ in range(len(queue)):r, c = queue.popleft()for dr, dc in directions:nr, nc = r + dr, c + dcif 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:grid[nr][nc] = 2fresh -= 1queue.append((nr, nc))minutes += 1return minutes if fresh == 0 else -1if __name__ == "__main__":grid1 = [[2, 1, 1],[1, 1, 0],[0, 1, 1]]grid2 = [[2, 1, 1],[0, 1, 1],[1, 0, 1]]print("grid1 minutes:", oranges_rotting(grid1))print("grid2 minutes:", oranges_rotting(grid2))
function orangesRotting(grid) {
const rows = grid.length;
const cols = grid[0].length;
const queue = [];
let fresh = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 2) {
queue.push([r, c]);
} else if (grid[r][c] === 1) {
fresh++;
}
}
}
if (fresh === 0) return 0;
let minutes = 0;
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let head = 0;
while (head < queue.length && fresh > 0) {
const levelSize = queue.length - head;
for (let i = 0; i < levelSize; i++) {
const [r, c] = queue[head++];
for (const [dr, dc] of directions) {
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === 1) {
grid[nr][nc] = 2;
fresh--;
queue.push([nr, nc]);
}
}
}
minutes++;
}
return fresh === 0 ? minutes : -1;
}
const grid1 = [
[2, 1, 1],
[1, 1, 0],
[0, 1, 1]
];
console.log("Minutes:", orangesRotting(grid1));import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public static int orangesRotting(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int fresh = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) {
queue.offer(new int[]{r, c});
} else if (grid[r][c] == 1) {
fresh++;
}
}
}
if (fresh == 0) return 0;
int minutes = 0;
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty() && fresh > 0) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
int[] curr = queue.poll();
int r = curr[0];
int c = curr[1];
for (int[] d : directions) {
int nr = r + d[0];
int nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
grid[nr][nc] = 2;
fresh--;
queue.offer(new int[]{nr, nc});
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
public static void main(String[] args) {
int[][] grid1 = {
{2, 1, 1},
{1, 1, 0},
{0, 1, 1}
};
System.out.println("Minutes: " + orangesRotting(grid1));
}
}#include <iostream>
#include <vector>
#include <queue>
int orangesRotting(std::vector<std::vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
std::queue<std::pair<int, int>> q;
int fresh = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) {
q.push({r, c});
} else if (grid[r][c] == 1) {
fresh++;
}
}
}
if (fresh == 0) return 0;
int minutes = 0;
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!q.empty() && fresh > 0) {
int levelSize = q.size();
for (int i = 0; i < levelSize; i++) {
auto [r, c] = q.front();
q.pop();
for (auto& d : dirs) {
int nr = r + d[0];
int nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
grid[nr][nc] = 2;
fresh--;
q.push({nr, nc});
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
int main() {
std::vector<std::vector<int>> grid = {
{2, 1, 1},
{1, 1, 0},
{0, 1, 1}
};
std::cout << "Minutes: " << orangesRotting(grid) << "\n";
return 0;
}#include <stdio.h>
int orangesRotting(int grid[3][3], int rows, int cols) {
int qR[100], qC[100];
int front = 0, rear = 0;
int fresh = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) {
qR[rear] = r;
qC[rear++] = c;
} else if (grid[r][c] == 1) {
fresh++;
}
}
}
if (fresh == 0) return 0;
int minutes = 0;
int dr[] = {1, -1, 0, 0};
int dc[] = {0, 0, 1, -1};
while (front < rear && fresh > 0) {
int levelSize = rear - front;
for (int i = 0; i < levelSize; i++) {
int r = qR[front];
int c = qC[front++];
for (int d = 0; d < 4; d++) {
int nr = r + dr[d];
int nc = c + dc[d];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
grid[nr][nc] = 2;
fresh--;
qR[rear] = nr;
qC[rear++] = nc;
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
int main(void) {
int grid[3][3] = {
{2, 1, 1},
{1, 1, 0},
{0, 1, 1}
};
printf("Minutes: %d\n", orangesRotting(grid, 3, 3));
return 0;
}