题目:
给你一个 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
提示:
思路:
一个位置所能存储水的量取决于该位置到边界各个点的路径中的各个格子的最高值的最小值。那么使用最小堆的思想,堆中最小高度的格子更新出来周围格子的储水量一定是满足要求的,将该格子出堆,将新更新的格子存储到最小堆中。使用宽度优先遍历即可得到最终结果。
class Solution {
public int trapRainWater(int[][] h) {
PriorityQueue<int[]> q = new PriorityQueue<>((a,b) -> a[0]-b[0]);
int res = 0;
int n = h.length, m = h[0].length;
int[] dx = new int[]{1,0,-1,0};
int[] dy = new int[]{0,1,0,-1};
boolean[][] st = new boolean[n][m];
for(int i = 0;i < n;i++) {
q.offer(new int[]{h[i][0],i,0});
st[i][0] = true;
q.offer(new int[]{h[i][m-1],i,m-1});
st[i][m-1] = true;
}
for(int i = 1;i < m -1;i++) {
q.offer(new int[]{h[0][i],0,i});
st[0][i] = true;
q.offer(new int[]{h[n-1][i],n-1,i});
st[n-1][i] = true;
}
while(q.size() > 0) {
int[] x = q.poll();
res += x[0] - h[x[1]][x[2]];
for(int i = 0;i < 4;i++) {
int xx = x[1] + dx[i],yy = x[2] + dy[i];
if(xx >= 0 && xx < n && yy >= 0 && yy < m && !st[xx][yy]) {
q.offer(new int[]{Math.max(h[xx][yy],x[0]),xx,yy});
st[xx][yy] = true;
}
}
}
return res;
}
}