在给定的?
m x n
?网格?grid
?中,每个单元格可以有以下三个值之一:
- 值?
0
?代表空单元格;- 值?
1
?代表新鲜橘子;- 值?
2
?代表腐烂的橘子。每分钟,腐烂的橘子?周围?4 个方向上相邻?的新鲜橘子都会腐烂。
返回?直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回?
-1
?。
class Solution {
public int orangesRotting(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int start = 2;
boolean status = false;
while (true) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == start) {
grid[i][j] = start + 1;
if(i > 0 && grid[i - 1][j] == 1){
grid[i - 1][j] = start + 1;
status = true;
}
if(j > 0 && grid[i][j - 1] == 1){
grid[i][j - 1] = start + 1;
status = true;
}
if(i < n - 1 && grid[i + 1][j] == 1){
grid[i + 1][j] = start + 1;
status = true;
}
if(j < m - 1 && grid[i][j + 1] == 1){
grid[i][j + 1] = start + 1;
status = true;
}
}
}
}
if(!status){
break;
}
start++;
status = false;
}
for (int[] ints : grid) {
for (int j = 0; j < m; j++) {
if (ints[j] == 1) {
return -1;
}
}
}
return start - 2;
}
}
?