题目描述:给你一个 m x n
的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
解题思路:从最外层访问,用优先队列记录最小高度
class Solution {
public int trapRainWater(int[][] heightMap) {
int m = heightMap.length, n = heightMap[0].length;
if(m <= 2 || n <= 2) {
return 0;
}
boolean[][] visited = 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]});
visited[i][j] = true;
}
}
}
int res = 0;
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, 1, 0, -1};
while (!pq.isEmpty()) {
int[] cur = pq.poll();
for (int k = 0; k < 4; k++) {
int x = cur[0] / n + dx[k], y = cur[0] % n + dy[k];
if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y]) {
if (cur[1] > heightMap[x][y]) {
res += cur[1] - heightMap[x][y];
}
pq.offer(new int[]{x*n+y, Math.max(heightMap[x][y], cur[1])});
visited[x][y] = true;
}
}
}
return res;
}
}