给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
该问题与原二维问题的差距还是挺大的
需要借鉴dijkstra算法的思想
python中使用堆队列结构能够较好地实现这个问题
从每次高度最小的点附近开始搜索
判断其附近的点是否能接到雨滴
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
if not heightMap :return 0
m,n = len(heightMap),len(heightMap[0])
if m<3 or n<3:return 0
state,move = [[False]*n for _ in range(m)],[(0,1),(0,-1),(1,0),(-1,0)]
height,res = [],0
for i in range(1,m-1):
heapq.heappush(height,(heightMap[i][0],i,0))
heapq.heappush(height,(heightMap[i][n-1],i,n-1))
for j in range(1,n-1):
heapq.heappush(height,(heightMap[0][j],0,j))
heapq.heappush(height,(heightMap[m-1][j],m-1,j))
while(height):
h,x,y = heapq.heappop(height)
for mo in move:
xx,yy = x+mo[0],y+mo[1]
if not 0<xx<m-1 or not 0<yy<n-1 or state[xx][yy]:
continue
state[xx][yy] = True
res += max(0,h-heightMap[xx][yy])
heapq.heappush(height,(max(h,heightMap[xx][yy]),xx,yy))
return res