题目描述:力扣
解题思路:
class Solution {
public static int orangesRotting(int[][] grid) {
int row = grid.length;
int col = grid[0].length;
int count = 0;
int res = 0;
Queue<int[]> queue = new LinkedList<>();
for(int i = 0; i < row; i++){
for(int j = 0 ; j < col; j++){
if(grid[i][j]==1){
count++;
}
else if(grid[i][j]==2){
queue.add(new int[]{i,j});
}
}
}
while(count>0&&!queue.isEmpty()){
int num = queue.size();
if(num == 0)
return 0;
res++;
for(int i = 0; i< num;i++){
int[] a = queue.poll();
int x = a[0];
int y = a[1];
if(x>0&&grid[x-1][y]==1){
grid[x-1][y]=2;
queue.add(new int[]{x-1,y});
count--;
}
if(y<col-1 && grid[x][y+1]==1){
grid[x][y+1]=2;
queue.add(new int[]{x,y+1});
count--;
}
if(x<row-1 && grid[x+1][y]==1){
grid[x+1][y]=2;
queue.add(new int[]{x+1,y});
count--;
}
if(y>0 && grid[x][y-1]==1){
grid[x][y-1]=2;
queue.add(new int[]{x, y-1});
count--;
}
}
}
if(count>0)
return -1;
else{
return res;
}
}
}