forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
trapping-rain-water-ii.py
60 lines (53 loc) · 1.74 KB
/
trapping-rain-water-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Time: O(m * n * log(m + n)) ~ O(m * n * log(m * n))
# Space: O(m * n)
# 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.
from heapq import heappush, heappop
class Solution(object):
def trapRainWater(self, heightMap):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
m = len(heightMap)
if not m:
return 0
n = len(heightMap[0])
if not n:
return 0
is_visited = [[False for i in xrange(n)] for j in xrange(m)]
heap = []
for i in xrange(m):
heappush(heap, [heightMap[i][0], i, 0])
is_visited[i][0] = True
heappush(heap, [heightMap[i][n-1], i, n-1])
is_visited[i][n-1] = True
for j in xrange(n):
heappush(heap, [heightMap[0][j], 0, j])
is_visited[0][j] = True
heappush(heap, [heightMap[m-1][j], m-1, j])
is_visited[m-1][j] = True
trap = 0
while heap:
height, i, j = heappop(heap)
for (dx, dy) in [(1,0), (-1,0), (0,1), (0,-1)]:
x, y = i+dx, j+dy
if 0 <= x < m and 0 <= y < n and not is_visited[x][y]:
trap += max(0, height - heightMap[x][y])
heappush(heap, [max(height, heightMap[x][y]), x, y])
is_visited[x][y] = True
return trap