407. Trapping Rain Water II

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.


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.

思路:从外向里遍历,因为是是从外面包住里面;
木桶理论,总的来说思路类似于1维情况下的2 pointer解法
import heapq

class Solution:
    def trapRainWater(self, a):
        """
        :type heightMap: List[List[int]]
        :rtype: int
        """
        if not a or not a[0]: return 0
        n,m=len(a),len(a[0])
        if n<=2 or m<=2: return 0
        q = []
        d=[[0,1],[0,-1],[1,0],[-1,0]]
        marked = [[False for _ in range(m)] for _ in range(n)]
        res = 0
        
        for i in range(m): 
            heapq.heappush(q, (a[0][i],0,i))
            heapq.heappush(q, (a[n-1][i],n-1,i))
            marked[0][i]=marked[n-1][i]=True
        for i in range(1,n-1): 
            heapq.heappush(q, (a[i][0],i,0))
            heapq.heappush(q, (a[i][m-1],i,m-1))
            marked[i][0]=marked[i][m-1]=True
            
        while q:
            h,i,j=heapq.heappop(q)
            for di,dj in d:
                ii,jj=i+di,j+dj
                if 0<=ii<n and 0<=jj<m and not marked[ii][jj]:
                    heapq.heappush(q, (max(a[ii][jj], h),ii,jj))
                    marked[ii][jj] = True
                    res += max(0, h-a[ii][jj])
        return res
    
s=Solution()
print(s.trapRainWater([
  [1,4,3,1,3,2],
  [3,2,1,3,2,4],
  [2,3,3,2,3,1]
]))
                    
                    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值