给你一个 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 * 104
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m, n = len(heightMap), len(heightMap[0])
vis = [[False] * n for _ in range(m)]
pq = []
for i in range(m):
for j in range(n):
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
heappush(pq, (heightMap[i][j], i, j))
vis[i][j] = True
ans = 0
while pq:
e = heappop(pq)
for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
i, j = e[1] + x, e[2] + y
if i >= 0 and i < m and j >= 0 and j < n and not vis[i][j]:
if heightMap[i][j] < e[0]:
ans += e[0] - heightMap[i][j]
vis[i][j] = True
heappush(pq, (max(heightMap[i][j], e[0]), i, j))
return ans
class Solution {
public int trapRainWater(int[][] heightMap) {
int m = heightMap.length, n = heightMap[0].length;
boolean[][] vis = new boolean[m][n];
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[0] - o2[0]);
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[] {heightMap[i][j], i, j});
vis[i][j] = true;
}
}
}
int ans = 0;
int[][] dirs = new int[][] {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
while (!pq.isEmpty()) {
int[] e = pq.poll();
for (int[] d : dirs) {
int i = e[1] + d[0], j = e[2] + d[1];
if (i >= 0 && i < m && j >= 0 && j < n && !vis[i][j]) {
if (heightMap[i][j] < e[0]) {
ans += e[0] - heightMap[i][j];
}
vis[i][j] = true;
pq.offer(new int[] {Math.max(heightMap[i][j], e[0]), i, j});
}
}
}
return ans;
}
}