Rotting Oranges
Medium
GraphBFSMatrix
Problem
A grid of cells: 0 = empty, 1 = fresh orange, 2 = rotten orange. Every minute, each rotten orange rots its 4-neighbours. Return the minutes until no fresh oranges remain, or −1 if some can never rot.
Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Example 3
Input: grid = [[0,2]]
Output: 0
Constraints
- 1 ≤ rows, cols ≤ 10
- cells are 0, 1, or 2
Approach — Graphs
This is a Graphs problem. The idea: explore the graph with BFS or DFS, marking nodes visited so you never process one twice. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(V + E) time.
Solution code
Python
class Solution:
def orangesRotting(self, grid):
from collections import deque
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, 0))
elif grid[r][c] == 1:
fresh += 1
minutes = 0
while q:
r, c, t = q.popleft()
minutes = max(minutes, t)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
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, t + 1))
return minutes if fresh == 0 else -1
Java
import java.util.*;
class Solution {
public int orangesRotting(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
Queue<int[]> q = new ArrayDeque<>();
int fresh = 0;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) q.offer(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) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
int[] cur = q.poll();
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
if (grid[nr][nc] != 1) continue;
grid[nr][nc] = 2;
fresh--;
q.offer(new int[]{nr, nc});
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Rotting Oranges interactively → ← All solutions