994 Rotting Oranges¶
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:
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.
Solution¶
Time: O(MN) -- We visit all cells in grid only once Space: O(MN) -- queue used to store at max all cells in the grid, each only once where matrix is M * N
:::tip Idea is to count initial number of fresh oranges, and then return as soon as the number drops to zero. Handle edge cases beforehand. :::
class Solution {
public int orangesRotting(int[][] grid) {
if(grid == null || grid.length == 0)
return 0;
int numOfMinutes = 0;
int countFreshOranges = 0;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == 1)
countFreshOranges++;
else if (grid[i][j] == 2)
queue.offer(new int [] {i,j});
}
}
if(countFreshOranges == 0)
return 0;
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
while(!queue.isEmpty()) {
int size = queue.size();
if(countFreshOranges == 0)
return numOfMinutes;
for(int i = 0 ; i < size ; i++) {
int[] point = queue.poll();
for(int dir[] : dirs) {
int newX = point[0] + dir[0];
int newY = point[1] + dir[1];
if(newX < 0 || newY < 0 || newX >= grid.length || newY >= grid[0].length || grid[newX][newY] != 1)
continue;
grid[newX][newY] = 2;
queue.offer(new int[]{newX , newY});
countFreshOranges--;
}
}
numOfMinutes++;
}
return -1;
}
}
Company¶
- Amazon