Rotting Oranges (LeetCode 994): Solution and Explanation

Medium
Array
Breadth First Search
Matrix

You get a grid where each cell is empty, holds a fresh orange, or holds a rotten one. Each minute, rot spreads from every rotten orange to its fresh neighbors up, down, left and right. Return how many minutes pass before no fresh orange is left, or -1 if some fresh orange can never be reached.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force is to simulate the clock literally. Each minute you scan the whole grid, find every fresh orange next to a rotten one, rot them all at once, and repeat until nothing changes. That works, but each minute costs a full O(m × n) scan and there can be O(m × n) minutes, so the total is O((m × n)²). Most of that scanning is wasted on cells that are far from any rot.

The key observation is that rot spreads exactly like a breadth-first search. An orange that rots at minute t only matters to its neighbors at minute t + 1, so if you keep a queue of the oranges that rotted most recently, you only ever look at the frontier. The twist compared with an ordinary BFS is that there can be several rotten oranges at the start, and they all spread at the same time. You handle that by putting every initially rotten orange in the queue before the search begins. This is called multi-source BFS, and it behaves as if one imaginary super-source rotted all of them at minute zero.

To count minutes, process the queue one level at a time. Everything in the queue at the start of a round rotted during the same minute, so you pop exactly that many cells, rot their fresh neighbors, and increment the clock once. Keeping a running count of fresh oranges gives you both an early stop (when it reaches zero) and the impossibility check at the end (when it never does).

Approach: Multi-source BFS

  1. Scan the grid once. Push the coordinates of every rotten orange into a deque and count the fresh oranges in fresh.
  2. Set minutes = 0 and define the four direction offsets.
  3. Loop while the queue is non-empty and fresh > 0. The second condition stops the clock as soon as the last fresh orange rots, so you never count an extra idle minute.
  4. At the start of each round increment minutes, then pop exactly len(queue) cells, which are the oranges that rotted in the previous minute.
  5. For each popped cell, check its four neighbors. If a neighbor is in bounds and equals 1, set it to 2 immediately, decrement fresh, and push it.
  6. After the loop, return minutes if fresh == 0, otherwise return -1 because some fresh orange was walled off by empty cells.

Step-by-step example

grid = [[2,1,1],[1,1,0],[0,1,1]]
  1. The initial scan finds one rotten orange at (0,0) and six fresh ones, so the queue holds [(0,0)] and fresh = 6.
  2. Minute 1: popping (0,0) rots (1,0) and (0,1). fresh drops to 4 and the queue is [(1,0), (0,1)].
  3. Minute 2: (1,0) rots (1,1), then (0,1) rots (0,2). fresh is 2 and the queue is [(1,1), (0,2)].
  4. Minute 3: (1,1) rots (2,1). (0,2) has only an empty neighbor below it, so nothing else changes. fresh is 1.
  5. Minute 4: (2,1) rots (2,2), and fresh reaches 0, so the loop stops and the function returns 4.

Code: Python, Java, C++

1class Solution:
2    def orangesRotting(self, grid: List[List[int]]) -> int:
3        m, n = len(grid), len(grid[0])
4        queue = deque()
5        fresh = 0
6
7        for i in range(m):
8            for j in range(n):
9                if grid[i][j] == 2:
10                    queue.append((i, j))
11                elif grid[i][j] == 1:
12                    fresh += 1
13
14        minutes = 0
15        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
16        while queue and fresh > 0:
17            minutes += 1
18            for _ in range(len(queue)):
19                r, c = queue.popleft()
20                for dr, dc in directions:
21                    nr, nc = r + dr, c + dc
22                    if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
23                        grid[nr][nc] = 2
24                        fresh -= 1
25                        queue.append((nr, nc))
26
27        return minutes if fresh == 0 else -1

Time and space complexity

Time

O(m × n)

Every cell is read once in the initial scan, and each orange enters the queue at most once because it is flipped to 2 before it is pushed. Each dequeued cell checks four neighbors, which is constant work.

Space

O(m × n)

In the worst case, such as a grid full of rotten oranges, the queue holds a number of cells proportional to the grid size. The grid itself is modified in place, so no separate visited set is needed.

Other approaches

Repeated full-grid simulation (time O((m × n)²), space O(m × n))

Scan the whole grid every minute, collect the fresh oranges that touch a rotten one, and rot them together. It is easy to reason about but rescans settled cells over and over, which only works because the grid here is at most 10 by 10.

BFS with a time stored per cell (time O(m × n), space O(m × n))

Instead of processing levels, push (row, col, time) tuples and track the largest time seen. The answer is the same and some people find it clearer, at the cost of storing an extra value per queue entry.

Common mistakes

  • Starting a separate BFS from each rotten orange and taking a maximum. The spreads overlap, so the right answer comes from running them simultaneously, which means seeding the queue with all sources at once.
  • Incrementing the clock after the final round even though nothing new rotted. The fresh > 0 loop condition prevents this; without it you return one more than the true answer.
  • Marking a neighbor rotten only when it is popped instead of when it is pushed. The same orange can then be enqueued twice from two directions and fresh is decremented twice.
  • Forgetting the case with no fresh oranges at all. The answer is 0, which the code returns because the loop never runs and fresh is already 0.

Frequently asked questions

Why is Rotting Oranges a BFS problem and not DFS?

The question asks for a minimum time, and rot spreads one step per minute in every direction at once. BFS explores cells in order of distance from the sources, so the level at which a cell is reached is exactly the minute it rots. DFS goes deep along one path and does not give you those distances directly.

When does Rotting Oranges return -1?

It returns -1 when at least one fresh orange is still fresh after the queue empties. That happens when a fresh orange, or a group of them, is completely separated from every rotten orange by empty cells or the grid edge.

What is multi-source BFS?

It is a breadth-first search that starts with several nodes in the queue instead of one. All of them are treated as distance zero, so the search computes each cell's distance to its nearest source in a single pass.

Can I solve it without modifying the grid?

Yes. Keep a separate visited matrix or a set of rotted coordinates and check it instead of writing 2 into the grid. The complexity is unchanged, but you use another O(m × n) of memory.