给你一个 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。
思路:木桶效应,容器能盛多少水由最短的一块木板决定。最外层一圈一定是装不了水的,是最早的木桶,找到最短的那块木板,这块木板往里遍历,就可以得到附近的位置可装多少水。
装好水之后,这块可做新的 "木板" (木板就是visited=True),木板高度为max(当前位置高度,临近最短木板高度)。
遍历 (x,y)周围的 (x,y-1),(x,y+1),(x-1,y),(x+1,y),可以设置一个数组[-1,0,1,0,-1] 快速遍历,详情见代码。
python
import heapq
from typing import List
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m,n = len(heightMap), len(heightMap[0])
visited = [[False] * n for _ in range(m)]
pq = []
for i in range(m):
visited[i][0] = True
heapq.heappush(pq, (heightMap[i][0], i*n))
visited[i][-1] = True
heapq.heappush(pq, (heightMap[i][-1], i*n+n-1))
for j in range(1, n-1):
visited[0][j] = True
heapq.heappush(pq, (heightMap[0][j], j))
visited[-1][j] = True
heapq.heappush(pq, (heightMap[-1][j], (m-1)*n+j))
weiyi=[-1,0,1,0,-1]
res = 0
while pq:
height,nxy=heapq.heappop(pq)
for k in range(4):
nx,ny=nxy//n+weiyi[k], nxy%n+weiyi[k+1]
if nx < m and ny < n and nx>=0 and ny>=0 and not visited[nx][ny]:
if heightMap[nx][ny] < height:
res += height-heightMap[nx][ny]
visited[nx][ny]=True
heapq.heappush(pq, (max(height,heightMap[nx][ny]), nx * n + ny))
return res