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 cell1: a fresh orange2: 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.
- m == grid.length, n == grid[i].length
- 1 <= m, n <= 10
- grid[i][j] is 0, 1, or 2
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.
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.
Approach
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.
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.
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
freshby 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.
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.
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
freshis 0, every orange rotted: returnt. - Otherwise some orange was walled off by empty cells: return -1.
Code in Python, C++ and Java
t to its minute, 2. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.t to its minute, 4. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.t to its minute, 2. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.t to its minute, 4. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.t to its minute, 0. All four neighbours are empty, outside the grid or already rotten, so nothing new rots from here.t is still 0, and that is the answer.Common pitfalls
Running a separate BFS from each rotten orange
for r, c in rotten:
bfs(r, c) # one search per sourcefor r, c in rotten:
q.append((r, c, 0)) # one shared queueRot 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
r, c = q.popleft() minutes += 1
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
r, c, t = q.popleft() grid[r][c] = 2
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
return t
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.
Edge cases
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.
The queue starts empty, so the loop never runs and fresh stays above 0: return -1.
Complexity
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.