力扣-994.腐烂的橘子
题目链接
994.腐烂的橘子
class Solution {int count = 0;Queue<int[]> queue = new LinkedList<>();public void bfs(int[][] grid, int i, int j) {int m = grid.length;int n = grid[0].length;if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1)return;grid[i][j] = 2;count--;queue.offer(new int[]{i, j});}public int orangesRotting(int[][] grid) {int res = 0;int m = grid.length;int n = grid[0].length;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (grid[i][j] == 1)count++;if (grid[i][j] == 2)queue.offer(new int[]{i, j});}}while (!queue.isEmpty()) {if (count == 0) return res;int before = count;int size = queue.size();for (int i = 0; i < size; i++) {int[] temp = queue.poll();bfs(grid, temp[0] + 1, temp[1]);bfs(grid, temp[0] - 1, temp[1]);bfs(grid, temp[0], temp[1] + 1);bfs(grid, temp[0], temp[1] - 1);}if (count == before) return -1;res++;}return count == 0 ? res : -1;}
}
小结:广度优先遍历,用队列存储。