在给定的网格中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotting-oranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这个题就是一个典型的深度还是广度的问题,这种扩散性的肯定是广度啊,一般迷宫这种单一路径的才是深度
BFS
public int orangesRotting(int[][] grid) { int M = grid.length; int N = grid[0].length; int count = 0; Queue<int[]> queue = new LinkedList<>(); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (grid[i][j] == 1) { count++; } else if (grid[i][j] == 2) { queue.add(new int[]{i, j}); } } } int round = 0; while (count > 0 && !queue.isEmpty()) { round++; int n = queue.size(); for (int i = 0; i < n; i++) { int[] orange = queue.poll(); int x = orange[0]; int y = orange[1]; if (x-1 >= 0 && grid[x-1][y] == 1) { grid[x-1][y] = 2; count--; queue.add(new int[]{x-1, y}); } if (x+1 < M && grid[x+1][y] == 1) { grid[x+1][y] = 2; count--; queue.add(new int[]{x+1, y}); } if (y-1 >= 0 && grid[x][y-1] == 1) { grid[x][y-1] = 2; count--; queue.add(new int[]{x, y-1}); } if (y+1 < N && grid[x][y+1] == 1) { grid[x][y+1] = 2; count--; queue.add(new int[]{x, y+1}); } } } if (count > 0) { return -1; } else { return round; } }
END 很简单,就是感染了一个接着把附近的几个也加入队列。