使用队列对矩阵进行广度优先搜索:
建立Orange类保存每个腐烂橘子的节点信息,包括该节点腐烂所需要的分钟数。
class Solution {
class Orange{
int x, y, minute;
public Orange(int _x, int _y, int _minute){
x = _x;
y = _y;
minute = _minute;
}
}
static int[][] dir ={{-1,0},{1,0},{0,-1},{0,1}};
public int orangesRotting(int[][] grid) {
int row = grid.length;
int col = grid[0].length;
int minute = 0;
Queue<Orange> queue = new LinkedList<>();
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if(grid[i][j] == 2)
queue.add(new Orange(i, j, minute));
}
}
while(!queue.isEmpty()){
Orange temp = queue.poll();
minute = temp.minute;
for(int k=0; k<4; k++){
int newX = temp.x+dir[k][0];
int newY = temp.y+dir[k][1];
if(newX>=0 && newX<row && newY>=0 && newY<col && grid[newX][newY] == 1){
grid[newX][newY] = 2;
queue.add(new Orange(newX, newY, temp.minute+1));
}
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if(grid[i][j] == 1)
return -1;
}
}
return minute;
}
}