Skip to content

Latest commit

 

History

History
54 lines (42 loc) · 1.84 KB

407.md

File metadata and controls

54 lines (42 loc) · 1.84 KB

407 Trapping Rain Water II

Description

link


Solution : HEAP

  • 准确性:
    • heap 当中代表的都是目前的边缘节点
    • pop 出来的是目前所有边缘节点当中 height 最小的
    • ������寻找四周没有被 visit 的节点,将高度差加入到答案中(由于四周都必定存在比其高的节点,故这个高度差一定可以装对应量的水)
    • 又因为目前这个节点是边缘节点,故寻找到的节点必然只能装同样的水
    • push 的过程将边缘和当前高度取最高,可以保证接下来的能装同样的水
  • 召回性:
    • 因为遍历到了每一个节点,故而一定能算出每个节点能装多少水
    • 至于不能装水的那些在遍历过程中全部被排除了

Code

Complexity T : O( mn )

class Solution:
    def trapRainWater(self, heightMap: List[List[int]]) -> int:
        if not heightMap or not heightMap[0]:
            return 0
        
        import heapq    
        m, n = len(heightMap), len(heightMap[0])
        heap = []
        visited = [[0]*n for _ in range(m)]

        # Push all the block on the border into heap
        for i in range(m):
            for j in range(n):
                if i == 0 or j == 0 or i == m-1 or j == n-1:
                    heapq.heappush(heap, (heightMap[i][j], i, j))
                    visited[i][j] = 1
        
        result = 0
        while heap:
            height, 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 and 0 <= y < n and not visited[x][y]:
                    result += max(0, height-heightMap[x][y])
                    heapq.heappush(heap, (max(heightMap[x][y], height), x, y))
                    visited[x][y] = 1
        return result