Rotting Oranges
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #994
Each grid cell is 0 (empty), 1 (fresh orange) or 2 (rotten orange). Every minute, each fresh orange adjacent (4-directionally) to a rotten one becomes rotten. Return the minimum number of minutes until no fresh orange remains, or −1 if that never happens.
Examples
text
[[2,1,1],
[1,1,0],
[0,1,1]] → 4
[[2,1,1],
[0,1,1],
[1,0,1]] → −1 (bottom-left orange is unreachable)
[[0,2]] → 0 (no fresh oranges)Hints
- All rotten oranges spread simultaneously, so start BFS from all of them at once.
- Each BFS level is one minute.
- Count fresh oranges up front; if any remain at the end, return −1.
Approach
Multi-source BFS: enqueue every initially rotten orange and count the fresh ones. Process the queue level by level; each level is one minute, in which you rot every fresh neighbor (decrementing the fresh count) and enqueue it. Stop when the queue empties. If the fresh count is 0, return the number of minutes elapsed; otherwise −1.
Complexity
Time: O(R·C). Space: O(R·C).
Python solution
from collections import deque
def orangesRotting(grid):
R, C = len(grid), len(grid[0])
q, fresh = deque(), 0
for r in range(R):
for c in range(C):
if grid[r][c] == 2:
q.append((r, c))
elif grid[r][c] == 1:
fresh += 1
minutes = 0
while q and fresh:
for _ in range(len(q)):
x, y = q.popleft()
for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= nx < R and 0 <= ny < C and grid[nx][ny] == 1:
grid[nx][ny] = 2
fresh -= 1
q.append((nx, ny))
minutes += 1
return minutes if fresh == 0 else -1JavaScript solution
function orangesRotting(grid) {
const R = grid.length, C = grid[0].length;
let q = [], fresh = 0;
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
if (grid[r][c] === 2) q.push([r, c]); else if (grid[r][c] === 1) fresh++;
}
let minutes = 0;
while (q.length && fresh) {
const next = [];
for (const [x, y] of q) {
for (const [nx, ny] of [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]) {
if (nx >= 0 && ny >= 0 && nx < R && ny < C && grid[nx][ny] === 1) { grid[nx][ny] = 2; fresh--; next.push([nx, ny]); }
}
}
q = next; minutes++;
}
return fresh === 0 ? minutes : -1;
}