题目:
Share
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
]
Return 4.
题解:
把这个二维矩阵想象成一个水桶,根据短板效应,桶能装的水取决于最短的那块板
def trapRainWater(self, heightMap):
“”"
:type heightMap: List[List[int]]
:rtype: int
“”"
heap,traped,m,n=[],0,len(heightMap),len(heightMap and heightMap[0])
for i in range(m):
for j in range(n):
if i in {0,m-1} or j in {0,n-1}:
heapq.heappush(heap,(heightMap[i][j],i,j))
heightMap[i][j]=-1
while heap:
h,i,j=heapq.heappop(heap)
for x,y in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):
if 0<x<m-1 and 0<y<n-1 and heightMap[x][y]!=-1:
traped+=max(h-heightMap[x][y],0)
heapq.heappush(heap,(max(h,heightMap[x][y]),x,y))
heightMap[x][y]=-1
return traped