题目地址
https://leetcode.cn/problems/rotting-oranges/description/
错误解法
class Solution {
public int orangesRotting(int[][] grid) {
//层序遍历
int ans = 0;
for (int i =0;i<grid.length;i++) {
for(int j =0;j<grid[0].length;j++){
boolean flag =false;
if(grid[i][j]==2){
//感染上边
if (i-1>=0&&grid[i-1][j]==1){
grid[i-1][j]=2;
flag=true;
}
//感染左边
if (j-1>=0&&grid[i][j-1]==1){
grid[i][j-1]=2;
flag=true;
}
//感染下边
if(j+1<grid[0].length&&grid[i][j+1]==1){
grid[i][j+1]=2;
flag=true;
}
//感染右边
if (i+1<grid.length&&grid[i+1][j]==1){
grid[i+1][j]=2;
flag=true;
}
}
if (flag){
ans++;
}
}
}
for (int i =0;i<grid.length;i++) {
for(int j =0;j<grid[0].length;j++){
if (grid[i][j]==1){
return -1;
}
}
}
return ans;
}
}
测试代码
public static void main(String[] args) {
int [][] as = {
{2,0,1,1,1,1,1,1,1,1},
{1,0,1,0,0,0,0,0,0,1},
{1,0,1,0,1,1,1,1,0,1},
{1,0,1,0,1,0,0,1,0,1},
{1,0,1,0,1,0,0,1,0,1},
{1,0,1,0,1,1,0,1,0,1},
{1,0,1,0,0,0,0,1,0,1},
{1,0,1,1,1,1,1,1,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
orangesRotting(as);
}
错误结果
错误原因
正确解法(BFS)
public int orangesRotting(int[][] grid) {
//定义每个元素周围都四个方向
int[][] direction = new int[][]{
{-1,0},//上
{0,1},//下
{0,-1},//左
{1,0}//右
};
//需要一个队列记录遍历得顶点
List<int[]> q = new ArrayList<>();
//行
int R = grid.length;
//列
int C = grid[0].length;
//新鲜橘子个个数 记录的好处是可以通过它等不等于0判断是否有橘子死活没有被感染
int fresh = 0;
for(int i=0;i<R;i++){
for (int j=0;j<C;j++){
if(grid[i][j]==1){
fresh++;
}
if (grid[i][j]==2){
q.add(new int[]{i,j});
}
}
}
int ans = -1;
while (!q.isEmpty()) {
ans++; // 经过一分钟
List<int[]> tmp = q;
q = new ArrayList<>();
for (int[] pos : tmp) { // 已经腐烂的橘子
for (int[] d : direction) { // 四方向
int i = pos[0] + d[0];
int j = pos[1] + d[1];
if (0 <= i && i < R && 0 <= j && j < C && grid[i][j] == 1) { // 新鲜橘子
fresh--;
grid[i][j] = 2; // 变成腐烂橘子
q.add(new int[]{i, j});
}
}
}
}
return fresh > 0 ? -1 : Math.max(ans, 0);
}