Rotting Oranges
The problem
Section titled “The problem”A grid holds 0 (empty), 1 (fresh orange) and 2 (rotten orange). Each minute, every
fresh orange next to a rotten one (up, down, left, right) becomes rotten. Return the
minutes until no fresh orange is left, or -1 if that never happens.
2 1 11 1 0 -> 40 1 1Key insight
Section titled “Key insight”Rot spreads outward from all rotten oranges at the same time, one step per minute. That is BFS where each level is a minute. Because several oranges start rotten, put all of them in the queue at the start (multi-source BFS) instead of running one BFS per source.
Count the fresh oranges first. Process the queue one level at a time; each level that
turns something rotten costs 1 minute. Every time a fresh orange rots, decrement the
count. At the end, a nonzero count means some orange was unreachable, so return -1.
Show solutionHide solution
from collections import deque
def oranges_rotting(grid: list[list[int]]) -> int: rows, cols = len(grid), len(grid[0]) queue = deque() fresh = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 2: queue.append((r, c)) # every rotten orange starts at minute 0 elif grid[r][c] == 1: fresh += 1
minutes = 0 while queue and fresh: minutes += 1 # one BFS level = one minute for _ in range(len(queue)): r, c = queue.popleft() for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)): if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1: grid[nr][nc] = 2 # rot it now so it is never queued twice fresh -= 1 queue.append((nr, nc)) return minutes if fresh == 0 else -1export function orangesRotting(grid: number[][]): number { const rows = grid.length; const cols = grid[0].length; // Array + head index: shift() is O(n) per call, so we never remove from the front. const queue: [number, number][] = []; let head = 0; 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]); // every rotten orange starts at minute 0 else if (grid[r][c] === 1) fresh++; } }
let minutes = 0; while (head < queue.length && fresh > 0) { minutes++; // one BFS level = one minute const levelEnd = queue.length; while (head < levelEnd) { const [r, c] = queue[head++]; for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) { if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === 1) { grid[nr][nc] = 2; // rot it now so it is never queued twice fresh--; queue.push([nr, nc]); } } } } return fresh === 0 ? minutes : -1;}import java.util.ArrayDeque;import java.util.Queue;
class Solution { public int orangesRotting(int[][] grid) { int rows = grid.length, cols = grid[0].length; Queue<int[]> queue = new ArrayDeque<>(); int fresh = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (grid[r][c] == 2) queue.add(new int[] {r, c}); // every rotten orange starts at minute 0 else if (grid[r][c] == 1) fresh++; } }
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int minutes = 0; while (!queue.isEmpty() && fresh > 0) { minutes++; // one BFS level = one minute for (int size = queue.size(); size > 0; size--) { int[] cell = queue.poll(); for (int[] d : dirs) { int nr = cell[0] + d[0], nc = cell[1] + d[1]; if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) { grid[nr][nc] = 2; // rot it now so it is never queued twice fresh--; queue.add(new int[] {nr, nc}); } } } } return fresh == 0 ? minutes : -1; }}Complexity
Section titled “Complexity”- Time: O(m·n) — each cell is queued at most once and checked a constant number of times.
- Space: O(m·n) — the queue can hold a large part of the grid. The grid is updated in place.
Watch out for
Section titled “Watch out for”- Off-by-one on minutes. Stop the loop as soon as no fresh oranges remain. Otherwise a
final level that rots nothing adds an extra minute. The loop condition
queue and freshhandles this, and it also makes “no fresh oranges at all” return 0. - Mark rotten when you enqueue, not when you pop. Otherwise the same orange is queued by several neighbors.
- Two different edge-case answers. No fresh oranges means
0; fresh oranges that can’t be reached (blocked by empty cells, or no rotten source) means-1. - Process by level. Take
len(queue)items per minute; don’t mix levels.
Variations
Section titled “Variations”01 Matrix (LeetCode 542)
Section titled “01 Matrix (LeetCode 542)”For each cell, find the distance to the nearest 0. The trick: multi-source BFS
again. Enqueue every 0 at distance 0 and let the distances spread outward.
Shortest Path in Binary Matrix (LeetCode 1091)
Section titled “Shortest Path in Binary Matrix (LeetCode 1091)”Shortest path from top-left to bottom-right through 0 cells, moving in 8 directions.
The trick: plain single-source BFS with 8 neighbors. The BFS level is the path
length, so return it the first time you reach the goal.