题目地址
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);}