Skip to main content

Rotting Oranges


Rotting Oranges: You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Example 1:

image

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 in the bottom left corner (row 2, column 0)
is never rotten, because rotting only happens 4-directionally.

Example 3:
Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges
at minute 0, the answer is just 0.

Constraints:
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.

Try this Problem on your own or check similar problems:

  1. Detonate the Maximum Bombs
  2. Escape the Spreading Fire
Solution:
class Solution {
int[][] directions = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 }};
public int orangesRotting(int[][] grid) {
int m = grid.length, n = grid[0].length;
Queue<int[]> q = new LinkedList<>();
int time = 0, numberOfOranges = 0;

for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(grid[i][j] == 2) q.add(new int[]{i, j});
if(grid[i][j] != 0) ++numberOfOranges;
}
}

if(numberOfOranges == 0) return 0;

while(!q.isEmpty()){
int size = q.size();
while(size-- > 0){
int[] current = q.poll();
--numberOfOranges;
for(int[] d: directions){
int newRow = current[0] + d[0];
int newCol = current[1] + d[1];
if(newRow < 0 || newRow >= m || newCol < 0 || newCol >= n || grid[newRow][newCol] != 1) continue;
grid[newRow][newCol] = 2;
q.add(new int[]{newRow, newCol});
}
}
++time;
}

return numberOfOranges == 0 ? time - 1 : -1;
}
}

Time/Space Complexity:
  • Time Complexity: O(mn)
  • Space Complexity: O(mn)

Explanation:

We implement the same BFS logic as we have seen in 01 Matrix of having first the initial candidates (already rotten oranges in this problem) and then searching for the next level of candidates which are neighbors of rotten oranges. We do that as long as we have a non-empty queue. We mark each visited neighbor by setting its value to 2 (rotten orange). Initially we also count the total number of oranges and then in our queue traversal we decrement that so we can use that information to see if we have visited all the oranges (or if it's not possible to visit them all). For each level we increase the time, and we return time - 1 as our final result since we don't count the first set of candidates (they're already rotten in the "0 minute"), otherwise if we couldn't reach all oranges, we return -1. The time and space complexity are proportional to the size of the grid O(mn).