LeetCode #994 Medium

Rotten Oranges

Rotten Oranges is LeetCode 994 (Medium). You are given an m x n grid where every cell is one of:

  • 0: an empty cell
  • 1: a fresh orange
  • 2: a rotten orange

Every minute, each fresh orange next to a rotten one (up, down, left or right, not diagonal) becomes rotten. Return the minimum number of minutes until no fresh orange is left, or -1 if that can never happen.

  • LeetCode's grid is at most 10 × 10, but GFG's version allows 500 × 500, so aim to handle each cell a constant number of times.
Constraints
  • m == grid.length, n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2
bfsmatrixqueue
Open on LeetCode ↗
02

Intuition

Rot spreads from every rotten orange at the same time, one step per minute. That is exactly how breadth-first search (BFS) grows: first every cell 1 step from the start, then every cell 2 steps away, and so on.

So put all the rotten oranges in the queue at minute 0 before the search begins. This is a multi-source BFS. Each fresh orange is first reached by its nearest rotten orange, and the minute it is reached is the minute it rots. The answer is the minute of the last orange to rot.

An orange that no rot can reach stays fresh forever. Counting the fresh oranges and crossing one off each time an orange rots tells you, at the end, whether any were missed.

How to spot this pattern

Reach for multi-source BFS when something spreads from several starting cells at once and the question asks how long it takes, or how far each cell is from the nearest start. 01 Matrix (LeetCode 542) and As Far from Land as Possible (LeetCode 1162) work the same way: queue every start first, then run one ordinary BFS.

03

Approach

Try it first

Before reading on: in the first example, which oranges rot at minute 1, and which at minute 2? Then decide what each queue entry should carry so the search knows an orange's minute without a separate clock.

1

Queue every rotten orange and count the fresh ones

Scan the grid once. Push each rotten cell as (r, c, 0), meaning rotten at minute 0, and count the fresh cells in fresh. All the sources go in before the search starts, so they spread together instead of one after another.

2

Pop a cell and rot its fresh neighbours

Pop (r, c, t) from the front of the queue. For each of the four neighbours that is inside the grid and fresh:

  • set it to 2,
  • lower fresh by 1,
  • push it with minute t + 1.

Mark it rotten when you push it, not when you pop it, so a second rotten neighbour cannot push it again.

3

Why the minutes come out right

Every push adds exactly 1 to the minute of the cell being popped, so the queue holds all minute t cells before any minute t + 1 cell. A fresh orange is therefore reached first by its nearest rotten orange, which is exactly when it would rot.

4

Return the minute or -1

When the queue is empty, t holds the minute of the last cell popped, which is the largest minute of all.

  • If fresh is 0, every orange rotted: return t.
  • Otherwise some orange was walled off by empty cells: return -1.
04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def orangesRotting(self, grid: List[List[int]]) -> int:
▶5 R, C = len(grid), len(grid[0])
▶6 q, fresh = deque(), 0
▶7 for r in range(R):
▶8 for c in range(C):
▶9 if grid[r][c] == 2:
▶10 q.append((r, c, 0))
▶11 elif grid[r][c] == 1:
▶12 fresh += 1
▶13 t = 0
▶14 while q:
▶15 r, c, t = q.popleft()
▶16 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
▶17 nr, nc = r + dr, c + dc
▶18 if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1:
▶19 grid[nr][nc] = 2
▶20 fresh -= 1
▶21 q.append((nr, nc, t + 1))
▶22 return t if fresh == 0 else -1
freshrotten, minute insideempty0120012minute t0fresh left6queue (front first)0,0min 01 rotten queued · 6 fresh
queue1every rotten orange, minute 0
fresh6counted in the same scan
Scan the grid once. Every rotten orange goes into the queue at minute 0 together, because rot spreads from all of them at the same time. The fresh oranges are only counted: 6 of them. The count is how the end will tell whether every orange was reached.
freshrotten, minute insideempty0120012minute t0fresh left6queue (front first)emptypop (0,0) · minute 0
popped(0,0)rotten at minute 0
t0minute of the popped orange
Take (0,0) from the front of the queue. It rotted at minute 0, so any fresh neighbour it reaches rots one minute later, at minute 1. It has 2 fresh neighbours.
freshrotten, minute insideempty01200112minute t0fresh left5queue (front first)1,0min 1rot (1,0) at minute 1
rotted(1,0)minute 1
fresh5one fewer
The neighbour (1,0) is fresh, so it rots at minute 1. It is marked rotten now, as it is pushed, so no other orange can push it a second time. Fresh oranges left: 5.
freshrotten, minute insideempty012001112minute t0fresh left4queue (front first)1,0min 10,1min 1rot (0,1) at minute 1
rotted(0,1)minute 1
fresh4one fewer
The neighbour (0,1) is fresh, so it rots at minute 1. It is marked rotten now, as it is pushed, so no other orange can push it a second time. Fresh oranges left: 4.
freshrotten, minute insideempty012001112minute t1fresh left4queue (front first)0,1min 1pop (1,0) · minute 1
popped(1,0)rotten at minute 1
t1minute of the popped orange
Take (1,0) from the front of the queue. It rotted at minute 1, so any fresh neighbour it reaches rots one minute later, at minute 2. It has 1 fresh neighbour.
freshrotten, minute insideempty0120011122minute t1fresh left3queue (front first)0,1min 11,1min 2rot (1,1) at minute 2
rotted(1,1)minute 2
fresh3one fewer
The neighbour (1,1) is fresh, so it rots at minute 2. It is marked rotten now, as it is pushed, so no other orange can push it a second time. Fresh oranges left: 3.
freshrotten, minute insideempty0120011122minute t1fresh left3queue (front first)1,1min 2pop (0,1) · minute 1
popped(0,1)rotten at minute 1
t1minute of the popped orange
Take (0,1) from the front of the queue. It rotted at minute 1, so any fresh neighbour it reaches rots one minute later, at minute 2. It has 1 fresh neighbour.
freshrotten, minute insideempty01200121122minute t1fresh left2queue (front first)1,1min 20,2min 2rot (0,2) at minute 2
rotted(0,2)minute 2
fresh2one fewer
The neighbour (0,2) is fresh, so it rots at minute 2. It is marked rotten now, as it is pushed, so no other orange can push it a second time. Fresh oranges left: 2.
freshrotten, minute insideempty01200121122minute t2fresh left2queue (front first)0,2min 2pop (1,1) · minute 2
popped(1,1)rotten at minute 2
t2minute of the popped orange
Take (1,1) from the front of the queue. It rotted at minute 2, so any fresh neighbour it reaches rots one minute later, at minute 3. It has 1 fresh neighbour.
freshrotten, minute insideempty012001211223minute t2fresh left1queue (front first)0,2min 22,1min 3rot (2,1) at minute 3
rotted(2,1)minute 3
fresh1one fewer
The neighbour (2,1) is fresh, so it rots at minute 3. It is marked rotten now, as it is pushed, so no other orange can push it a second time. Fresh oranges left: 1.
freshrotten, minute insideempty012001211223minute t2fresh left1queue (front first)2,1min 3pop (0,2) · minute 2 · no fresh neighbour
popped(0,2)rotten at minute 2
t2minute of the popped orange
Take (0,2) from the front of the queue and set t to its minute, 2. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.
freshrotten, minute insideempty012001211223minute t3fresh left1queue (front first)emptypop (2,1) · minute 3
popped(2,1)rotten at minute 3
t3minute of the popped orange
Take (2,1) from the front of the queue. It rotted at minute 3, so any fresh neighbour it reaches rots one minute later, at minute 4. It has 1 fresh neighbour.
freshrotten, minute insideempty0120012112234minute t3fresh left0queue (front first)2,2min 4rot (2,2) at minute 4
rotted(2,2)minute 4
fresh0one fewer
The neighbour (2,2) is fresh, so it rots at minute 4. It is marked rotten now, as it is pushed, so no other orange can push it a second time. Fresh oranges left: 0.
freshrotten, minute insideempty0120012112234minute t4fresh left0queue (front first)emptypop (2,2) · minute 4 · no fresh neighbour
popped(2,2)rotten at minute 4
t4minute of the popped orange
Take (2,2) from the front of the queue and set t to its minute, 4. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.
freshrotten, minute insideempty0120012112234minute t4fresh left0queue (front first)emptyfresh 0 → return 4
fresh0
return4minute of the last orange popped
The queue is empty and the fresh count is 0, so every orange rotted. The last orange popped rotted at minute 4. BFS pops cells in order of minute, so that is the largest one: the answer is 4.
05

Common pitfalls

Running a separate BFS from each rotten orange

✗ Wrong
for r, c in rotten:
    bfs(r, c)  # one search per source
✓ Right
for r, c in rotten:
    q.append((r, c, 0))  # one shared queue

Rot spreads from all rotten oranges at once. Searching from one source at a time lets the first search claim cells that a closer source would reach sooner, so the minutes come out too large, and it repeats the work once per source.

Adding a minute for every orange popped

✗ Wrong
r, c = q.popleft()
minutes += 1
✓ Right
r, c, t = q.popleft()
# neighbours get t + 1

Several oranges rot in the same minute. A counter that grows on every pop counts oranges, not minutes. Either carry the minute with each cell, as here, or process the queue one whole level at a time and add 1 per level.

Marking a cell rotten only when it is popped

✗ Wrong
r, c, t = q.popleft()
grid[r][c] = 2
✓ Right
grid[nr][nc] = 2
q.append((nr, nc, t + 1))

A fresh orange next to two rotten ones would be pushed twice before either copy is popped, and fresh would drop twice for one orange. Marking it when it is pushed lets each cell enter the queue once.

Forgetting to count the fresh oranges

✗ Wrong
return t
✓ Right
return t if fresh == 0 else -1

Without the count there is no way to tell "everything rotted" from "the spread stopped early", and a walled-off orange would wrongly return a minute count instead of -1.

06

Edge cases

No fresh oranges at the start, e.g. [[0,2]]

Nothing has to rot, so the answer is 0. t is never raised above 0 and fresh is already 0, so no special case is needed.

Fresh oranges but no rotten one, e.g. [[1]]

The queue starts empty, so the loop never runs and fresh stays above 0: return -1.

07

Complexity

Time
O(m · n)
Space
O(m · n)
Every cell is pushed and popped at most once, and each pop checks four neighbours. The queue can hold most of the grid when many oranges rot in the same minute.
08

Rotten Oranges FAQ

What are the steps?
  • Seed: push every rotten orange with minute 0 and count the fresh ones.
  • Spread: pop a cell; rot each fresh neighbour, push it with minute + 1, and lower the fresh count.
  • Answer: when the queue empties, return the last minute if the fresh count is 0, else -1.
  • Complexity: O(m · n) time and space.
Most solutions loop over the queue one level at a time. Is storing the minute with each cell the same?

Yes. The level loop (for _ in range(len(q))) adds 1 to the minute after each full level. Storing the minute inside each queue entry gives the same numbers, because a cell's minute is always its parent's minute plus 1. Watch for one detail in the level version: it often counts one extra level after the last orange rots, so it returns minutes - 1 or only counts levels that rotted something.

Can it be solved without a queue?

Yes, by simulating minute by minute: scan the whole grid, rot every fresh orange that touches a rotten one, and repeat until a scan changes nothing. Newly rotted oranges must be marked with a different value (for example 3) during the scan, or rot would spread several steps in one minute. Each scan is O(m · n) and there can be up to m · n minutes, so it is O((m · n)²).

Why does the Python solution use deque?

Because list.pop(0) shifts every remaining element, so each pop costs O(length of the queue) and the whole search can slow to O((m · n)²). deque.popleft() is O(1), which keeps the search at O(m · n).

Why BFS and not DFS?

DFS follows one path as deep as it can, so it can reach an orange along a long path before the short one. It then has to store the smallest minute per cell and revisit cells when a shorter path appears. BFS reaches every cell first by its shortest path, so each cell is settled the first time it is seen.