Rotting Oranges

Work out how many minutes rot needs to reach every fresh orange in a grid, or show that some orange never rots.

A grid of m rows and n columns holds oranges. Each cell is 0 for an empty cell, 1 for a fresh orange or 2 for a rotten orange. Every minute, each fresh orange directly above, below, left or right of a rotten orange becomes rotten too. Return the smallest number of minutes after which no fresh orange is left, or -1 if some fresh orange never rots. A cell is written as (row, column), counting from 0.

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
Explanation: the orange at (2,0) has only empty cells next to it, so the rot can never reach it.
Example 3
Input: grid = [[0,2]]
Output: 0
Explanation: there is no fresh orange to begin with.
Solution

The Idea

One mouldy orange in a crate soon spoils the oranges pressed against it, and those spoil their own neighbours a little later. The rot moves outward from the bad orange, one ring of oranges at a time. This problem asks how long the crate lasts: when does the last fresh orange turn?

Look at the picture below. It is the grid of Example 1, and the number in each orange is the minute in which it rots. The teal 0 at (0,0) is the orange that is rotten at the start.

The Example 1 grid with rows and columns numbered 0 to 2. The rotten orange at (0,0) starts. In minute 1, (0,1) and (1,0) rot; in minute 2, (0,2) and (1,1); in minute 3, (2,1); in minute 4, (2,2), and no fresh orange is left.

In minute 1, the two oranges touching (0,0) rot: (0,1) to its right and (1,0) below it. In minute 2, their fresh neighbours (0,2) and (1,1) follow. The cell (1,2) above (2,2) is empty, so the rot cannot come from above. It has to go down through (2,1) in minute 3 and only then reach (2,2) in minute 4, the row labelled "minute 4" on the right. That is the answer, 4.

So the minute an orange rots is the number of steps it lies from the rotten orange, counting only steps up, down, left or right through other oranges. That raises two questions. How do we find these step counts without replaying the whole grid minute by minute? And how do we notice an orange like (2,0) in Example 2, which no path of oranges connects to the rot?

The picture already shows the answer to the first one. Every orange that rots in minute 2 touches one that rotted in minute 1, and every minute 1 orange touches the starting one. So we can work through the oranges ring by ring: first all oranges one step away, then all oranges two steps away, and so on. Visiting cells in this order, finishing every cell at one distance before moving one step further, is called breadth-first search, or BFS for short. It goes wide first, not deep.

The second question has a simple answer: count the fresh oranges at the start and subtract one each time an orange rots. If the rings run out while the count is still above 0, some orange was never reached, and the answer is -1.

Solution Approach

Turning that idea into code means settling four things: finding the cells next to an orange, starting from every rotten orange at once instead of rescanning the grid each minute, telling one minute from the next, and stopping.

Finding the cells next to an orange

Which cells can a rotten orange reach in one minute? Only the four that share a side with it. You can see the grid as a graph: each cell is a point, called a vertex, and two cells that share a side are joined by a line, called an edge. Many graph problems first build an adjacency list, a list of neighbours for every vertex. Here there is no need, because the neighbours of (row, column) are always (row + 1, column), (row - 1, column), (row, column + 1) and (row, column - 1).

The code keeps these four moves, one step down, up, right or left, as pairs of offsets in an array, and adds each pair to the current cell. A neighbour that falls outside the grid, such as (-1, 0) next to (0,0), is skipped.

Starting from every rotten orange at once

Why not just copy the rules of the problem? Each minute, scan the whole grid and rot every fresh orange next to a rotten one. That works, but each scan reads all m × n cells, and a long winding line of oranges can take a number of minutes close to the number of cells. The work then grows with the square of the grid size.

BFS instead keeps the oranges whose turn it is to spread in a queue, a list where items join at the back and leave from the front. Here the queue is an ArrayDeque of {row, column} pairs. Before the spread starts, every rotten orange goes into the queue. That matters when there are several: in the single row 2 1 1 1 2, the rot comes from both ends at the same time, and the middle orange rots in minute 2. Starting BFS from several cells together like this is called multi-source BFS.

Telling one minute from the next

How does the code know where one minute ends? At the start of a minute, the queue holds exactly the oranges that rotted in the minute before. So the code reads the queue's size once, takes that many oranges from the front, and lets each one rot its fresh neighbours. The newly rotten oranges join the back of the queue and wait for the next minute.

A neighbour is set to 2 the moment it joins the queue. Another rotten orange next to it then sees a 2, not a 1, so the same orange is never queued twice.

Deciding when to stop

When is the spread over? A variable fresh holds the number of fresh oranges and goes down by one each time an orange rots. The spread goes on only while fresh is above 0 and the queue still has oranges. If fresh reaches 0, the minutes counted so far are the answer. If the queue empties first, the oranges still fresh can never be reached, so the answer is -1.

Java Solution

The method orangesRotting works in these steps:

  1. First, scan the grid with two loops, one over the rows and one inside it over the columns. Each rotten orange goes into queue, an ArrayDeque of {row, column} pairs, and each fresh orange adds 1 to fresh.
  2. Set minutes to 0 and store the four moves in directions. A while loop then runs as long as fresh is above 0 and queue is not empty. Each pass of this loop is one minute, so it starts by adding 1 to minutes.
  3. Inside, a for loop reads queue.size() once into size and takes exactly that many cells from the front of the queue: the oranges that rotted in the minute before.
  4. For each cell taken, an inner loop tries the four moves in directions. A neighbour that is inside the grid and fresh is set to 2, fresh goes down by 1, and the neighbour joins the back of the queue.
  5. When the while loop ends, return minutes if fresh is 0, and -1 otherwise.

The main method prints each grid row by row, then its answer: the three examples, the single row with rotten oranges at both ends, a lone fresh orange, and a grid with no orange at all.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class RottingOranges {

    public static int orangesRotting(int[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        Deque<int[]> queue = new ArrayDeque<>();
        int fresh = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] == 2) {
                    queue.add(new int[] {r, c});      // every rotten orange starts the spread
                } else if (grid[r][c] == 1) {
                    fresh++;
                }
            }
        }
        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        int minutes = 0;
        while (fresh > 0 && !queue.isEmpty()) {
            minutes++;
            for (int size = queue.size(); size > 0; size--) {   // only this minute's oranges
                int[] cell = queue.poll();
                for (int[] d : directions) {
                    int r = cell[0] + d[0];
                    int c = cell[1] + d[1];
                    if (r >= 0 && r < rows && c >= 0 && c < cols && grid[r][c] == 1) {
                        grid[r][c] = 2;                 // rots now, so it is queued only once
                        fresh--;
                        queue.add(new int[] {r, c});
                    }
                }
            }
        }
        return fresh == 0 ? minutes : -1;
    }

    static void run(int[][] grid) {
        for (int[] row : grid) {
            StringBuilder line = new StringBuilder();
            for (int v : row) {
                line.append(v).append(' ');
            }
            System.out.println(line.toString().trim());
        }
        System.out.println("minutes: " + orangesRotting(grid));
        System.out.println();
    }

    public static void main(String[] args) {
        run(new int[][] {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}});
        run(new int[][] {{2, 1, 1}, {0, 1, 1}, {1, 0, 1}});
        run(new int[][] {{0, 2}});
        run(new int[][] {{2, 1, 1, 1, 2}});
        run(new int[][] {{1}});
        run(new int[][] {{0}});
    }
}

Running it prints:

Output
2 1 1
1 1 0
0 1 1
minutes: 4

2 1 1
0 1 1
1 0 1
minutes: -1

0 2
minutes: 0

2 1 1 1 2
minutes: 2

1
minutes: -1

0
minutes: 0

The first grid is Example 1, and minutes: 4 matches the orange marked 4 in the picture. The second grid ends with minutes: -1. Its bottom row, 1 0 1, starts with an orange that has a 0 above it and a 0 to its right, so it is still fresh when the queue runs out. For 0 2 the answer is 0, because fresh is 0 from the start and the while loop never runs.

The row 2 1 1 1 2 gives 2. Both rotten ends were in the queue from the start, so the middle orange, two steps from each end, rots in minute 2. The lone 1 gives -1, since there is no rotten orange to queue at all, and the grid 0 gives 0, since there is nothing to rot.

Why does the while loop check fresh > 0 and not only that the queue has oranges? In Example 1, the orange at (2,2) joins the queue in minute 4. With only the queue check, the loop runs a fifth time to let (2,2) spread, and nothing rots. Trying that version printed 5 for Example 1, 1 for 0 2 and 3 for 2 1 1 1 2.

Complexity

The work is one scan of the grid, plus the spread, in which each orange joins the queue at most once.

  • Time: O(m × n), because the first scan reads each of the m × n cells once, and in the spread each orange leaves the queue at most once and checks its four neighbours.
  • Space: O(m × n), because the queue can hold a large share of the cells at once, every cell when the whole grid starts rotten. The grid itself records which oranges have rotted, so no second grid is needed.

The same spread from several starting cells fills in distances in Walls and Gates.