8.21 - hard - 79

407. Trapping Rain Water II

利用外围边界,依次朝里面找,只是新加入heap的值需要取其原来值和新值比较高的那个点作为高度。

class Solution(object):
    def trapRainWater(self, heightMap):
        """
        :type heightMap: List[List[int]]
        :rtype: int
        """
        if not heightMap:
            return 0
        # 利用heap来做
        visited = [[False for _ in range(len(heightMap[0]))] for _ in range(len(heightMap))]
        
        # init
        heap = []
        for i in range(len(heightMap)):
            for j in range(len(heightMap[0])):
                if i == 0 or i == len(heightMap) - 1 or j == 0 or j == len(heightMap[0]) - 1:
                    heapq.heappush(heap, [heightMap[i][j], i, j])
                    visited[i][j] = True
        
        # find the lowest one
        res = 0
        while heap:
            cur, i, j = heapq.heappop(heap)
            for x, y in [[i+1, j], [i-1, j], [i, j+1], [i, j-1]]:
                if 0 <= x < len(heightMap) and 0 <= y < len(heightMap[0]) and not visited[x][y]:
                    res += max(0, cur - heightMap[x][y])
                    heapq.heappush(heap, [max(cur, heightMap[x][y]), x, y])
                    visited[x][y] = True
        
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,059评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,521评论 2 36
  • 这节课主要讲heap,stack和deque的运用。heap主要是保持顺序上,每次取出一个元素还可以保持剩下元素的...
    健时总向乱中忙阅读 280评论 0 0
  • 312. Burst Balloons: 区间dp+backtracking315. Count of Small...
    健时总向乱中忙阅读 349评论 0 0
  • 2016年我在深圳遇到了你,一个让我自己觉得卑微的你,感觉你就跟明星一样只能远观不可亵玩… 我曾...
    大宝_0666阅读 245评论 0 0

友情链接更多精彩内容