# 地图中的最高点
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
class Solution1765 {
public static void main(String[] args) {
int[][] res = new Solution1765().highestPeak(new int[][]{
{0, 1}, {0, 0}
});
System.out.println(Arrays.deepToString(res));
}
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int[][] highestPeak(int[][] isWater) {
int m = isWater.length, n = isWater[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < m; ++i) {
Arrays.fill(ans[i], -1); // -1 表示该格子尚未被访问过
}
Queue<int[]> queue = new ArrayDeque<int[]>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (isWater[i][j] == 1) {
ans[i][j] = 0;
queue.offer(new int[]{i, j}); // 将所有水域入队
}
}
}
while (!queue.isEmpty()) {
int[] p = queue.poll();
for (int[] dir : dirs) {
int x = p[0] + dir[0], y = p[1] + dir[1];
if (0 <= x && x < m && 0 <= y && y < n && ans[x][y] == -1) {
ans[x][y] = ans[p[0]][p[1]] + 1;
queue.offer(new int[]{x, y});
}
}
}
return ans;
}
}
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
39
40
41
42
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
39
40
41
42