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
Output: 4
Example 2
Output: -1
Explanation: the orange at (2,0) has only empty cells next to it, so the rot can never reach it.
Example 3
Output: 0
Explanation: there is no fresh orange to begin with.
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.
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{row, column}2 1 1 1 2
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 freshfreshfresh
Java Solution
The method orangesRotting
- First, scan the grid with two loops, one over the rows and one inside it over the columns. Each rotten orange goes into
, anqueue ofArrayDeque pairs, and each fresh orange adds 1 to{row, column} .fresh - Set
to 0 and store the four moves inminutes . Adirections loop then runs as long aswhile is above 0 andfresh is not empty. Each pass of this loop is one minute, so it starts by adding 1 toqueue .minutes - Inside, a
loop readsfor once intoqueue.size() and takes exactly that many cells from the front of the queue: the oranges that rotted in the minute before.size - For each cell taken, an inner loop tries the four moves in
. A neighbour that is inside the grid and fresh is set to 2,directions goes down by 1, and the neighbour joins the back of the queue.fresh - When the
loop ends, returnwhile ifminutes is 0, and -1 otherwise.fresh
The main
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:
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: 4minutes: -11 0 10 2freshwhile
The row 2 1 1 1 210
Why does the whilefresh > 00 22 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