leetcode 407 储水II

题目:
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值