Trapping Rain Water II

本文介绍了一种计算二维矩阵地形中降雨后积水体积的方法。通过使用堆数据结构找到最低的障碍物,以此来确定周围区域可以积累的水量。文章详细解释了算法流程,并提供了Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n x m non-negative integers representing an elevation map 2d where the area of each cell is 1 x 1, compute how much water it is able to trap after raining.

这是一道非常有意思的题目。如果明白了灌水类问题的核心思之后则可以明白,当前位置可灌的水为周围最低的bar(包括灌完水的)决定的.每次用堆找到一个最低的bar(弹出这个最低的bar,意思是处理过)之后该bar周围找点,如果没有加入过堆,且值小于堆顶值,则进行灌水.代码如下:

class Solution:
    # @param heights: a matrix of integers
    # @return: an integer
    def trapRainWater(self, heights):
        if not heights or not heights[0]:
            return 0
        import heapq
        heap = []
        m = len(heights)
        n = len(heights[0])
        visited = [[False] * n for i in xrange(m)]
        
        for i in xrange(n):
            visited[0][i] = True
            heapq.heappush(heap, (heights[0][i],(0,i)))
            if m > 1:
                visited[-1][i] = True
                heapq.heappush(heap, (heights[-1][i],(m-1,i)))
        for j in xrange(m):
            visited[j][0] = True
            heapq.heappush(heap, (heights[j][0], (j,0)))
            if n > 1:
                visited[j][-1] = True
                heapq.heappush(heap, (heights[j][-1], (j, n-1)))
        
        area = 0
        dx = [1, 0, -1, 0]
        dy = [0, -1, 0, 1]
        
        while heap:
            cur = heapq.heappop(heap)
            for i in xrange(4):
                x = cur[1][0] + dx[i]
                y = cur[1][1] + dy[i]
                if x >= 0 and y>= 0 and x < m and y < n and not visited[x][y]:
                    visited[x][y] = True
                    if heights[x][y] < cur[0]:
                        area += cur[0] - heights[x][y]
                        heapq.heappush(heap, (cur[0],(x,y)))
                    else:
                        heapq.heappush(heap, (heights[x][y],(x,y)))
                        
        return area

 注意不用担心斜对角线漏水~

转载于:https://www.cnblogs.com/sherylwang/p/5647474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值