In a given grid, each cell can have one of three values:
- the value
0
representing an empty cell; - the value
1
representing a fresh orange; - the value
2
representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) 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
instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
思路:跟Zombie in Matrix 一模一样: 把腐烂的苹果先收集到queue里面,然后level order扩展,记住queue里面是腐烂的苹果,所以如果最后没有苹果可以感染了,那么会level空+1,最后level要减去1;T:O(m*n), S:O(m*n)
错误点:没有弄清楚题目的输出,面试的时候一定要跟面试官确认输入和输出,走例子;
class Solution {
public int orangesRotting(int[][] grid) {
Queue<int[]> queue = new LinkedList<>();
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == 2) {
queue.offer(new int[]{i, j});
visited[i][j] = true;
}
}
}
int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] node = queue.poll();
int x = node[0];
int y = node[1];
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n && !visited[nx][ny] && grid[nx][ny] == 1) {
visited[nx][ny] = true;
queue.offer(new int[]{nx, ny});
}
}
}
step++;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(!visited[i][j] && grid[i][j] == 1) {
return -1;
}
}
}
return step == 0 ? 0 : step - 1;
}
}