LeetCode 994. 腐烂的橘子

994. 腐烂的橘子

解题思路

「多源 BFS 问题」先统计所有新鲜橘子数量,同时将初始所有腐烂橘子作为BFS第一层起点,然后按每分钟扩散感染相邻新鲜橘子,每感染一个就减少新鲜计数,直到没有新鲜橘子或无法继续扩散,最终返回耗时或 -1

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

public int orangesRotting(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int fresh = 0;
List<int[]> q = new ArrayList<>();
for(int i = 0; i < m; i ++) {
for(int j = 0; j < n; j ++) {
if(grid[i][j] == 1) {
fresh ++;
} else if(grid[i][j] == 2) {
q.add(new int[]{i, j});
}
}
}

int res = 0;
while(fresh > 0 && !q.isEmpty()) {
res ++;
List<int[]> tmp = q;
q = new ArrayList<>();
for(int[] pos : tmp) {
for(int[] d: DIRECTIONS) {
int i = pos[0] + d[0];
int j = pos[1] + d[1];
if(0 <= i && i < m && 0 <= j && j < n && grid[i][j] == 1) {
fresh --;
grid[i][j] = 2;
q.add(new int[]{i, j});
}
}
}
}
return fresh > 0 ? -1 : res;
}
}

LeetCode 994. 腐烂的橘子
https://sowink.cn/2026/02/08/LeetCode-994-腐烂的橘子/
作者
Xurx
发布于
2026年2月8日
许可协议