题目描述
在给定的网格中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
示例1:
输入:[[2,1,1],[1,1,0],[0,1,1]]
输出:4
示例2:
输入:[[2],[1],[1],[1],[2],[1],[1]]
输出:2
Sample Code 1
…||grid[i-1][j]-grid[i][j]>1)是为了缩减天数,避免像示例2那样正面循环过来后天数不合理过高的情况
class Solution {
int[][] grid;
int row;
int column;
public int orangesRotting(int[][] grid) {
this.grid=grid;
this.row=grid.length;
this.column=grid[0].length;
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
if(grid[i][j]==2)
bfs(i,j,2);
int res=0;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(grid[i][j]==1) return -1;
res=Math.max(res,grid[i][j]);
}
}
if(res==0) return 0;
return res-2;
}
public void bfs(int i,int j,int val){
grid[i][j]=val;
if(i>0&&(grid[i-1][j]==1||grid[i-1][j]-grid[i][j]>1))
bfs(i-1,j,val+1);
if(j>0&&(grid[i][j-1]==1||grid[i][j-1]-grid[i][j]>1))
bfs(i,j-1,val+1);
if(i<row-1&&(grid[i+1][j]==1||grid[i+1][j]-grid[i][j]>1))
bfs(i+1,j,val+1);
if(j<column-1&&(grid[i][j+1]==1||grid[i][j+1]-grid[i][j]>1))
bfs(i,j+1,val+1);
}
}
Sample Code 2
class Solution {
int[] dr = new int[]{-1, 0, 1, 0};
int[] dc = new int[]{0, -1, 0, 1};
public int orangesRotting(int[][] grid) {
int R = grid.length, C = grid[0].length;
Queue<Integer> queue = new ArrayDeque();
Map<Integer, Integer> depth = new HashMap();
for (int r = 0; r < R; ++r)
for (int c = 0; c < C; ++c)
if (grid[r][c] == 2) {
int code = r * C + c;
queue.add(code);
depth.put(code, 0);
}
int ans = 0;
while (!queue.isEmpty()) {
int code = queue.remove();
int r = code / C, c = code % C;
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k];
int nc = c + dc[k];
if (0 <= nr && nr < R && 0 <= nc && nc < C && grid[nr][nc] == 1) {
grid[nr][nc] = 2;
int ncode = nr * C + nc;
queue.add(ncode);
depth.put(ncode, depth.get(code) + 1);
ans = depth.get(ncode);
}
}
}
for (int[] row: grid)
for (int v: row)
if (v == 1)
return -1;
return ans;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotting-oranges