Skip to content

Rotting Oranges

MediumLeetCode #994Time O(m·n)Space O(m·n)

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 1
1 1 0 -> 4
0 1 1

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 -1
  • 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.
  • 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 fresh handles 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.

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.