本文共 2241 字,大约阅读时间需要 7 分钟。
要解决这个问题,我们需要模拟橘子腐烂传播的过程。使用广度优先搜索(BFS)来逐层扩散腐烂,直到所有新鲜橘子都被腐蚀。每次处理一个腐烂橘子,会检查其四个邻居,将新鲜邻居腐化并加入队列。
import java.util.Deque;import java.util.ArrayDeque;public class orangesRotting02 { public static int orangesRotting(int[][] grid) { int rows = grid.length; int cols = grid[0].length; Dequequeue = new ArrayDeque<>(); int count = 0; // 初始化队列,记录初始腐烂点,并统计新鲜点数 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 2) { queue.add(new int[]{i, j}); } else if (grid[i][j] == 1) { count++; } } } int res = 0; while (!queue.isEmpty() && count > 0) { res++; int size = queue.size(); for (int i = 0; i < size; i++) { int[] temp = queue.poll(); int r = temp[0], c = temp[1]; // 上 if (r > 0 && grid[r - 1][c] == 1) { grid[r - 1][c] = 2; count--; queue.add(new int[]{r - 1, c}); } // 下 if (r < rows - 1 && grid[r + 1][c] == 1) { grid[r + 1][c] = 2; count--; queue.add(new int[]{r + 1, c}); } // 左 if (c > 0 && grid[r][c - 1] == 1) { grid[r][c - 1] = 2; count--; queue.add(new int[]{r, c - 1}); } // 右 if (c < cols - 1 && grid[r][c + 1] == 1) { grid[r][c + 1] = 2; count--; queue.add(new int[]{r, c + 1}); } } } return count == 0 ? res : -1; }}
这个方法通过BFS高效地处理了每个橘子的腐蚀过程,确保在最少的分钟内完成任务。如果无法完成任务,如示例中的某些情况,会返回-1。
转载地址:http://idhqz.baihongyu.com/