public int orangesRotting(int[][] grid) {
//网格高度
int m = grid.length;
//网格宽度
int n = grid[0].length;
//放腐烂橘子的坐标
Queue<int[]> queue = new LinkedList<>();
//新鲜橘子的数量
int fresh = 0;
//找出腐烂的橘子
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 2) {
//把腐烂的橘子加入到队列中
queue.offer(new int[]{i, j});
} else if (grid[i][j] == 1) {
//新鲜的橘子
fresh++;
}
}
}
//如果没有腐烂的橘子,直接返回0
if (fresh == 0) {
return 0;
}
//计算时间
int times = -1;
//方向数组
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
//当前队列中腐烂橘子的数量
int size = queue.size();
times++;//需要的时间
while (size-- > 0) {
//腐烂的橘子
int[] poll = queue.poll();
//遍历当前腐烂橘子的上下左右四个方向
for (int[] dir : dirs) {
int x = poll[0] + dir[0];
int y = poll[1] + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
//新鲜橘子数量减1
fresh--;
//让他腐烂
grid[x][y] = 2;
//腐烂之后加入到队列中
queue.offer(new int[]{x, y});
}
}
}
}
return fresh == 0 ? times : -1;
}