Skip to content

Rotting Oranges

Count the minutes until every orange rots, with all rotten oranges spreading at once in a level-by-level BFS.

MediumGraph BFS and DFS
Solve on LeetCode

The problem

You get a grid grid where 0 is an empty cell, 1 is a fresh orange and 2 is a rotten one. Every minute, each fresh orange directly above, below, left or right of a rotten orange becomes rotten. Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never rot.

Input grid = [[2, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 2]]

Output 2

Both rotten oranges spread at the same time. After minute 1 the four oranges next to them are rotten, and after minute 2 the last three are.

Input grid = [[1, 0, 2]]

Output -1

The empty cell keeps the fresh orange away from the rotten one, so it never rots.

How to spot the pattern

  • Something spreads one step per time unit, from several starting points at once.
  • You need the time until the spread reaches the last cell, which is a shortest-distance question.

The idea

The minute an orange rots is its distance, in steps, from the nearest orange that was rotten at the start. BFS finds such distances, and putting every rotten orange in the queue before starting (a multi-source BFS) makes all of them spread together. Process the queue one level at a time: each level is one minute, and the number of levels it takes to reach the last fresh orange is the answer.

Brute force: Simulate minute by minute by scanning the whole grid for fresh oranges next to rotten ones, which takes O((m * n)^2) time when the rot has to travel far.

Step by step

  1. 1Put every rotten orange in a queue and count the fresh ones.
  2. 2While the queue is not empty and fresh oranges remain, add one minute.
  3. 3Take out exactly the oranges that were in the queue when this minute started.
  4. 4Rot each fresh neighbor they have, lower the fresh count and add that neighbor to the queue.
  5. 5At the end, return the minutes if no fresh orange is left, and -1 otherwise.

See the pattern move

The graph bfs and dfs pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        queue = deque()
        fresh = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 2:
                    queue.append((r, c))  # every rotten orange starts spreading at minute 0
                elif grid[r][c] == 1:
                    fresh += 1

        minutes = 0
        while queue and fresh > 0:
            minutes += 1
            for _ in range(len(queue)):  # one level of the BFS is one minute
                r, c = queue.popleft()
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                        grid[nr][nc] = 2
                        fresh -= 1
                        queue.append((nr, nc))

        return minutes if fresh == 0 else -1

Complexity

Time

O(m * n)

Space

O(m * n)

Each orange enters the queue at most once and checks four neighbors; the queue can hold O(m * n) cells.

Watch out for

  • Running a separate BFS from each rotten orange instead of letting all of them spread at once.
  • Counting one minute too many by adding a minute for a last level in which nothing rots; stopping when no fresh orange is left avoids it.
  • Returning -1 when there are no fresh oranges at all; the answer is 0.

Follow-up questions

How do you find the minute each orange rots?

Keep a distance grid instead of only changing values to 2: a newly rotten orange's minute is its neighbor's minute plus 1, exactly as in 01 Matrix.

What if crossing some cells took longer than one minute?

Steps no longer cost the same, so plain BFS breaks. Use Dijkstra's algorithm with a priority queue ordered by time.

In Hinglish

Saare rotten oranges ko ek saath queue mein daalo, phir level by level BFS chalao; har level ek minute hai. Aakhir mein koi fresh bacha toh -1 return karo.

Related problems