Problem
A grid contains 0 (empty), 1 (fresh orange) and 2 (rotten orange). Every minute, any fresh orange that is four-directionally adjacent to a rotten one becomes rotten. Return the minimum minutes until every orange is rotten, or -1 if that is impossible.
Original: LeetCode 994: Rotting Oranges.
Examples
Example 1
`grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]``4`Example 2
`grid = [[2, 1, 1], [0, 1, 1], [1, 0, 1]]``-1`Example 3
`grid = [[0, 2]]``0`Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j]is0,1, or2.
Hints
Hint 1
All initially rotten oranges act at the same time, so this is not a single-source walk. Empty cells block the rot.
Hint 2
Simultaneous infection on a grid is multi-source BFS. The answer is the maximum distance from any fresh orange to the nearest rotten one.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Repeatedly scan the whole grid and rot neighbours, once per minute. That is correct but slower, O(minutes * rows * cols).
Optimal. Enqueue every rotten cell at time 0, then BFS, incrementing time when a level ends. Count fresh oranges so you can detect leftovers.
Alternative. You can also run a separate BFS from each fresh orange, but that is worse than one multi-source search.
Complexity
- Time
- O(rows * cols)
O(rows * cols) time and O(rows * cols) space for the queue in the worst case.
- Space
- O(rows * cols)
Code
from collections import deque
def oranges_rotting(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
q = deque()
fresh = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
q.append((r, c))
elif grid[r][c] == 1:
fresh += 1
minutes = 0
dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
while q and fresh:
for _ in range(len(q)):
r, c = q.popleft()
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
q.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1
if __name__ == "__main__":
assert oranges_rotting([[2, 1, 1], [1, 1, 0], [0, 1, 1]]) == 4
assert oranges_rotting([[2, 1, 1], [0, 1, 1], [1, 0, 1]]) == -1
assert oranges_rotting([[0, 2]]) == 0
print("ok")import java.util.ArrayDeque;
public class RottingOranges {
static int orangesRotting(int[][] grid) {
int rows = grid.length, cols = grid[0].length, fresh = 0;
var q = new ArrayDeque<int[]>();
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 minutes = 0;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!q.isEmpty() && fresh > 0) {
int size = q.size();
for (int i = 0; i < size; i++) {
int[] cur = q.remove();
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != 1) continue;
grid[nr][nc] = 2;
fresh--;
q.add(new int[] {nr, nc});
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
public static void main(String[] args) {
if (orangesRotting(new int[][] {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}}) != 4) throw new AssertionError();
if (orangesRotting(new int[][] {{2, 1, 1}, {0, 1, 1}, {1, 0, 1}}) != -1) throw new AssertionError();
if (orangesRotting(new int[][] {{0, 2}}) != 0) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: [[2,1,1],[1,1,0],[0,1,1]] takes 4 minutes; [[2,1,1],[0,1,1],[1,0,1]] returns -1 because a fresh orange is boxed in; [[0,2]] returns 0 because nothing is fresh.
- If the grid starts with no fresh oranges, return 0 without incrementing minutes.
Follow-ups
- Walls-and-gates, or 01 Matrix, is the same multi-source BFS idea from every source cell.
Interview script
"All rotten oranges start together, so I run one BFS from every rotten cell at once. Each level of the queue is one minute. If a fresh orange is never reached, I return -1."
Source: LeetCode 994: Rotting Oranges
Sources (1)
- LeetCode 994: Rotting Orangesleetcode.com