题目
给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
示例 1:
输入: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
输出: 4
解释: 下雨后,雨水将会被上图蓝色的方块中。总的接雨水量为1+2+1=4。
示例 2:
输入: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
输出: 10
提示:
m == heightMap.length
n == heightMap[i].length
1 <= m, n <= 200
0 <= heightMap[i][j] <= 2 * 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water-ii
一、解题思路
看层二维坐标下数正方体,用头顶标数法,先把最外围的一圈作为围栏, 选择一个最低的围栏, 如果这个围栏的邻节点都比它大, 此围栏可删除,邻节点作为新的围栏;
如果邻节点比它小, 那么邻节点可储蓄的水为 二者高度之差, 此时在邻节点设置围栏,高度为当前围栏高度即可。
water[i][j]=max(heightMap[i],min(water[i−1][j],water[i+1][j],water[i][j−1],water[i][j+1]))
二、结果
1.注意点
- 考虑特殊情况,行或列小于3的时候是接不到水的
- 标记数组visit 看是否被访问,访问后用true标记,保证最矮的外层节点与内层节点求高度
2.java代码
代码如下(示例):
class Solution {
public int trapRainWater(int[][] heightMap) {
//考虑特殊情况,行或列小于3的时候是接不到水的
if (heightMap.length <= 2 || heightMap[0].length <= 2) {
return 0;
}
//构建队列,将最外圈放入队列,同时标记数组visit 看是否被访问
int m = heightMap.length;
int n = heightMap[0].length;
boolean[][] visit = new boolean[m][n];
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
pq.offer(new int[]{i * n + j, heightMap[i][j]});
visit[i][j] = true; //访问过后设为true
}
}
}
int res = 0;
int[] dirs = {-1, 0, 1, 0, -1};
//循环从pq取出元素,遍历其上下左右节点,如果找到比它小的内部节点,就灌水到等高
//元素出队,入队内部节点,标记visit
while (!pq.isEmpty()) {
int[] curr = pq.poll();
for (int k = 0; k < 4; ++k) {
int nx = curr[0] / n + dirs[k];
int ny = curr[0] % n + dirs[k + 1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny]) {
if (curr[1] > heightMap[nx][ny]) {
res += curr[1] - heightMap[nx][ny];
}
pq.offer(new int[]{nx * n + ny, Math.max(heightMap[nx][ny], curr[1])});
visit[nx][ny] = true;
}
}
}
return res;
}
}
总结
是前几天欠下的吗,今天的题目巨难,但也学习到了新思路!!!
打开第八天,坚持坚持 加油加油!!!!!