Ecommet

Rotting Oranges

Medium Problem 102 of 151 Java and Python

Problem

In an m × n grid, each cell is 0 (empty), 1 (fresh orange) or 2 (rotten orange). Every minute, any fresh orange next to a rotten one (up, down, left, right) becomes rotten.

Return the minimum number of minutes until no fresh orange is left, or -1 if that is impossible.

Example 1

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

Example 2

Input
grid = [[2, 1, 1], [0, 1, 1], [1, 0, 1]]
Output
-1
Why
The bottom-left orange can never be reached.

Example 3

Input
grid = [[0, 2]]
Output
0
Why
No fresh oranges to begin with.

Constraints

  • 1 ≤ m, n ≤ 10

Explanation

Rot spreads one step per minute from every rotten orange at the same time. That is a BFS whose first level is all the rotten oranges together (multi-source BFS). Each BFS level is one minute.

Count fresh oranges up front; if any are left when the BFS ends, return -1.

Approach 1 · Naive

Simulate minute by minute

  • Time O((m · n)²)
  • Space O(m · n)

Each minute, scan the whole grid and rot every fresh orange next to a rotten one. Stop when nothing changes.

  1. Repeat: collect every fresh cell that has a rotten neighbour.
  2. If none, stop; otherwise rot them all and add a minute.
  3. At the end, return -1 if any fresh orange remains.
Java
import java.util.*;

class Solution {
    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int minutes = 0;
        while (true) {
            List<int[]> toRot = new ArrayList<>();
            for (int r = 0; r < m; r++) {
                for (int c = 0; c < n; c++) {
                    if (grid[r][c] == 1 && ((r > 0 && grid[r - 1][c] == 2) || (r < m - 1 && grid[r + 1][c] == 2)
                        || (c > 0 && grid[r][c - 1] == 2) || (c < n - 1 && grid[r][c + 1] == 2))) {
                        toRot.add(new int[] { r, c });
                    }
                }
            }
            if (toRot.isEmpty()) {
                break;
            }
            for (int[] cell : toRot) {
                grid[cell[0]][cell[1]] = 2;
            }
            minutes++;
        }
        for (int[] row : grid) {
            for (int v : row) {
                if (v == 1) {
                    return -1;
                }
            }
        }
        return minutes;
    }
}
Python
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        minutes = 0
        while True:
            to_rot = [
                (r, c) for r in range(m) for c in range(n)
                if grid[r][c] == 1 and any(
                    0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 2
                    for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)))
            ]
            if not to_rot:
                break
            for r, c in to_rot:
                grid[r][c] = 2
            minutes += 1
        return -1 if any(1 in row for row in grid) else minutes

Approach 2 · Optimal

Multi-source BFS

  • Time O(m · n)
  • Space O(m · n)

Put every rotten orange in the queue first, then BFS level by level; each level is a minute.

  1. Enqueue all rotten cells and count fresh ones.
  2. While the queue is not empty and fresh oranges remain: process one whole level, rotting fresh neighbours (decrementing fresh), then add a minute.
  3. Return minutes if fresh == 0, else -1.
Java
import java.util.*;

class Solution {
    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        Deque<int[]> queue = new ArrayDeque<>();
        int fresh = 0;
        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (grid[r][c] == 2) {
                    queue.add(new int[] { r, c });
                } else if (grid[r][c] == 1) {
                    fresh++;
                }
            }
        }
        int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
        int minutes = 0;
        while (!queue.isEmpty() && fresh > 0) {
            for (int i = queue.size(); i > 0; i--) {
                int[] cell = queue.poll();
                for (int[] d : dirs) {
                    int r = cell[0] + d[0];
                    int c = cell[1] + d[1];
                    if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] == 1) {
                        grid[r][c] = 2;
                        fresh--;
                        queue.add(new int[] { r, c });
                    }
                }
            }
            minutes++;
        }
        return fresh == 0 ? minutes : -1;
    }
}
Python
from collections import deque

class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        queue = 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 queue and fresh:
            for _ in range(len(queue)):
                r, c = queue.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
                        fresh -= 1
                        queue.append((nr, nc))
            minutes += 1
        return minutes if fresh == 0 else -1

Complexity compared

ApproachTimeSpace
Naive Simulate minute by minuteO((m · n)²)O(m · n)
Optimal Multi-source BFSO(m · n)O(m · n)

Key takeaways

  • Multi-source BFS: when spreading starts from several places at once, seed the queue with all of them.
  • Loop while fresh > 0, or you count an extra minute after the last orange rots.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem