解题思路:
因为要记录轮数(分钟数),所以不能一口气遍历到底,所以不能用深搜(bfs),而要用广搜(bfs,层序遍历)。
先记录下新鲜橘子数,并用一个队列记录腐烂橘子的坐标。
每轮遍历腐烂橘子(使用过的腐烂橘子需要出队),并向四周影响,使得四周的新鲜橘子变为腐烂橘子(新鲜橘子数减1,队列中加入新的腐烂橘子的坐标)。
- class Solution {
- public int orangesRotting(int[][] grid) {
- Queue<int[]> queue = new LinkedList<>();
- int fresh = 0;
- for (int r = 0; r < grid.length; r++) {
- for (int c = 0; c < grid[0].length; c++) {
- if (grid[r][c] == 1) fresh++;
- else if (grid[r][c] == 2) queue.add(new int[] { r, c });
- }
- }
-
- int minutes = 0;
- while (fresh > 0 && !queue.isEmpty()) {
- minutes++;
- int n = queue.size();// for循环中queue大小不断变化,需要提前暂存
- for (int i = 0; i < n; i++) {
- int[] orange = queue.poll();
- int r = orange[0];
- int c = orange[1];
- if (r - 1 >= 0 && grid[r - 1][c] == 1) {
- grid[r - 1][c] = 2;
- fresh--;
- queue.add(new int[] { r - 1, c });
- }
- if (r + 1 < grid.length && grid[r + 1][c] == 1) {
- grid[r + 1][c] = 2;
- fresh--;
- queue.add(new int[] { r + 1, c });
- }
- if (c - 1 >= 0 && grid[r][c - 1] == 1) {
- grid[r][c - 1] = 2;
- fresh--;
- queue.add(new int[] { r, c - 1 });
- }
- if (c + 1 < grid[0].length && grid[r][c + 1] == 1) {
- grid[r][c + 1] = 2;
- fresh--;
- queue.add(new int[] { r, c + 1 });
- }
- }
- }
- if (fresh > 0) return -1;
- else return minutes;
- }
- }