Rotting Oranges

Medium

Topics
GraphBFSMatrix

In an m x n grid each cell is 0 (empty), 1 (fresh orange), or 2 (rotten). Every minute, a fresh orange adjacent (4-directionally) to a rotten one becomes rotten. Return the minutes until no fresh orange remains, or -1 if impossible.

Example 1

0012112·2·34012
rotten at minute 0minute it rots
Each cell is labelled with the minute it turns rotten; · is an empty cell.
2D grid — one row per line.
Input:  grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2

00121·232∞·4012
rotten at minute 0minute it rotsnever rots
Input:  grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1

Constraints

  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Rot spreads outward one layer per minute from ALL currently-rotten oranges simultaneously — that is textbook multi-source BFS. The number of BFS levels is the answer.

Approach

  1. Push every rotten orange into the initial queue and count fresh oranges.
  2. Process the queue level by level; each level is one minute, rotting fresh neighbours.
  3. If any fresh remain at the end, return -1; else return the elapsed minutes.

Dry Run

grid  2 1 1
      1 1 0
      0 1 1
Every already-rotten orange goes into the queue before the first minute, so the
spread starts from all of them at once. Here there is one, at (0,0), and 6 fresh.
  minute 1   rots (1,0) and (0,1)        fresh left 4
  minute 2   rots (1,1) and (0,2)        fresh left 2
  minute 3   rots (2,1)                  fresh left 1
  minute 4   rots (2,2)                  fresh left 0
answer 4
The `for _ in range(len(q))` is what makes a minute a minute. The length is read
ONCE at the top of the level, so the oranges pushed during this minute are not
processed until the next -- drop that and the queue becomes a plain flood fill
with no notion of elapsed time.
Two boundary cases are handled without special branches. On 2 1 1 / 0 1 1 / 1 0 1
the fresh orange at (2,0) is walled off, the queue empties with fresh still 1, and
the answer is -1. And on a grid with no fresh oranges the loop condition
`while q and fresh` is false immediately, so minutes stays 0 -- which is the right
answer, not -1, because there was nothing left to rot.
Cells are marked rotten at push time, so nothing is ever queued twice and each
cell enters at most once. That is the O(m*n).

Complexity

  • Time — O(m*n): each cell enters the queue at most once.
  • Space — O(m*n): the BFS queue.

Common Pitfalls

  • A grid with zero fresh oranges answers 0, not -1 — check before subtracting.

Full Solution — all languages

class Solution:
    def orangesRotting(self, grid):
        from collections import deque
        R,C=len(grid),len(grid[0])
        q=deque(); fresh=0
        for r in range(R):
            for c in range(C):
                if grid[r][c]==2: q.append((r,c))
                elif grid[r][c]==1: fresh+=1
        minutes=0
        dirs=[(1,0),(-1,0),(0,1),(0,-1)]
        while q and fresh:
            for _ in range(len(q)):
                r,c=q.popleft()
                for dr,dc in dirs:
                    nr,nc=r+dr,c+dc
                    if 0<=nr<R and 0<=nc<C and grid[nr][nc]==1:
                        grid[nr][nc]=2; fresh-=1; q.append((nr,nc))
            minutes+=1
        return minutes if fresh==0 else -1
SensAI
Beta
Tap the mic to stop voice mode