LeetCode1765. 地图中的最高点(多源bfs)
作者:互联网
文章目录
1.
2.题解
首先是想用dfs写,对每个点进行dfs取四周最小的点的值再加1就是此点的高度,但是这样做不出来。
用多源bfs写,以每个水域为原点进行bfs,下一层的高度一定比当前层高。
public int[][] highestPeak(int[][] g) {
int m = g.length, n = g[0].length;
int[][] ans = new int[m][n];
Deque<int[]> d = new ArrayDeque<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (g[i][j] == 1) d.addLast(new int[]{i, j});
ans[i][j] = g[i][j] == 1 ? 0 : -1; //-1代表未访问过
}
}
int[][] dirs = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}};
int h = 1; //每一层的高度
while (!d.isEmpty()) {
int size = d.size();
while (size-- > 0) {//对每一层进行遍历
int[] info = d.pollFirst();
int x = info[0], y = info[1];
for (int[] di : dirs) {
int nx = x + di[0], ny = y + di[1];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
if (ans[nx][ny] != -1) continue;
ans[nx][ny] = h;
d.addLast(new int[]{nx, ny});
}
}
h++;
}
return ans;
}
标签:nx,int,bfs,ny,ans,new,LeetCode1765,多源,size 来源: https://blog.csdn.net/weixin_45736160/article/details/122740354