Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
就是四面都是围墙,从最低的往里走;
如果里面有更低的,当然就可以蓄水,蓄水的量就是围墙最低 减去 此处的高度;
如果里面的比当前围墙高,那这个方向的围墙高度就增加了。
然后永远围墙最低的地方开始搜,最后就能把整个水池搜一遍
class Solution:
def trap(self, height) -> int:
l,r,wall,lower,res = 0,len(height)-1,0,0,0
while (l<r):
lower = min(height[l],height[r])
res += max(0, wall-lower)
(l,r) = (l+1,r) if height[l] <= height[r] else (l,r-1)
wall = max(wall,lower)
return res
s = Solution()
print(s.trap([0,1,0,2,1,0,1,3,2,1,2,1]))
--------------------------------------------------------
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.
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.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
before the rain.
After the rain, water is trapped between the blocks. The total volume of water trapped is 4.
Constraints:
1 <= m, n <= 110
0 <= heightMap[i][j] <= 20000
------------------------------------------
import heapq
class Solution:
def trapRainWater(self, heightMap) -> int:
rows,cols = len(heightMap),len(heightMap[0]) if heightMap else 0
if (rows == 0 or cols == 0):
return 0
pq,res,height = [],0,0
for i in range(rows):
for j in range(cols):
if (i in {0,rows-1} or j in {0,cols-1}):
pq.append((heightMap[i][j],i,j))
heightMap[i][j] = -1
heapq.heapify(pq)
while (pq):
ch,x,y = heapq.heappop(pq)
height = max(ch, height) # bug2: height = max(nh, height)
for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
nx,ny = x+dx,y+dy
if (0<=nx<rows and 0<=ny<cols and heightMap[nx][ny] >= 0): #bug4: heightMap[nx][ny] > 0
nh = heightMap[nx][ny]
res += max(0, (height-nh))
heapq.heappush(pq,(nh,nx,ny))
heightMap[nx][ny] = -1 #bug1
#break #bug3: 周围是要保证都走一遍的
return res