0:00 / 0:00

How many minutes until every orange rots? Start a breadth-first search from all the rotten ones at once, one ring per minute.

▼

The problem

LeetCode 994 (Medium). A grid holds 0 (empty), 1 (a fresh orange) or 2 (a rotten orange). Every minute, each rotten orange rots the fresh oranges next to it (up, down, left, right). Return the minutes until no fresh orange is left, or -1 if that can never happen.

Example (new for the remake, two rotten corners so the walkthrough shows a multi-source start): [[2,1,1,0,1],[1,0,1,1,1],[1,1,1,0,2]] → 4.

from collections import deque

def orangesRotting(grid):
    m, n = len(grid), len(grid[0])
    q = deque((r, c) for r in range(m) for c in range(n) if grid[r][c] == 2)
    fresh = sum(row.count(1) for row in grid)
    minutes = 0
    while q and fresh:
        for _ in range(len(q)):          # one level
            r, c = q.popleft()
            for nr, nc in (r+1, c), (r-1, c), (r, c+1), (r, c-1):
                if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
                    grid[nr][nc] = 2     # rot it
                    fresh -= 1
                    q.append((nr, nc))
        minutes += 1
    return minutes if fresh == 0 else -1
TRY IT ON LEETCODE ▶

The solution

from collections import deque

def orangesRotting(grid):
    m, n = len(grid), len(grid[0])
    q = deque((r, c) for r in range(m) for c in range(n) if grid[r][c] == 2)
    fresh = sum(row.count(1) for row in grid)
    minutes = 0
    while q and fresh:
        for _ in range(len(q)):          # one level
            r, c = q.popleft()
            for nr, nc in (r+1, c), (r-1, c), (r, c+1), (r, c-1):
                if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
                    grid[nr][nc] = 2     # rot it
                    fresh -= 1
                    q.append((nr, nc))
        minutes += 1
    return minutes if fresh == 0 else -1

Transcript

Rotting Oranges. Each cell of a crate is empty, a fresh orange, or a rotten one. Every minute, each rotten orange spoils the fresh oranges next to it: up, down, left and right. How many minutes until none are fresh? If some can never rot, return minus one.

This crate starts with two rotten oranges and ten fresh. The rot spreads in waves from both corners, and after four minutes the last one turns: the answer is four. Now take two oranges out. The bottom one is walled in by empty cells and never rots, so the answer is minus one.

The slow way scans the whole grid every minute, spoiling neighbors, until nothing changes. In a winding crate the rot moves one cell per scan, so there can be about as many scans as cells, and the work grows with the square of the grid.

Instead, run one breadth first search from every rotten orange at once. Queue them all at minute zero. Each level of the queue is one minute: pop the level, and push the fresh neighbors it spoils. So each orange rots when the nearest rot reaches it. Keep a count of fresh ones, to spot any left behind.

Back to our crate. Minute zero: two rotten in the queue, ten fresh. Minute one: they spoil three, seven left. Minute two: those spoil four more, three left. Minute three: two more, one left. Minute four: the last one turns. Zero fresh, four minutes.

In code, queue the rotten oranges and count the fresh ones. While the queue has oranges and some are still fresh, process one level: check each orange's four neighbors, rot every fresh one, lower the count, and queue it. Then add a minute. Return the minutes if nothing is fresh, otherwise minus one.

Each cell joins the queue at most once and checks four neighbors, so the time is order m times n. The queue can hold most of the grid, so the space is order m times n too.

Start every rot at once, and count the waves. That's Rotting Oranges.