Skip to content

Commit 8b21443

Browse files
committed
[LeetCode Sync] Runtime - 132 ms (51.86%), Memory - 20.1 MB (81.51%)
1 parent 5ea54c1 commit 8b21443

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution:
2+
def trapRainWater(self, heightMap: List[List[int]]) -> int:
3+
if not heightMap or not heightMap[0]:
4+
return 0
5+
6+
7+
# Initial
8+
# Board cells cannot trap the water
9+
m, n = len(heightMap), len(heightMap[0])
10+
if m < 3 or n < 3:
11+
return 0
12+
13+
14+
# Add Board cells first
15+
heap = []
16+
for i in range(m):
17+
for j in range(n):
18+
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
19+
heapq.heappush(heap, (heightMap[i][j], i, j))
20+
heightMap[i][j] = -1
21+
22+
23+
# Start from level 0
24+
level, res = 0, 0
25+
26+
while heap:
27+
height, x, y = heapq.heappop(heap)
28+
level = max(height, level)
29+
30+
for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
31+
if 0 <= i < m and 0 <= j < n and heightMap[i][j] != -1:
32+
heapq.heappush(heap, (heightMap[i][j], i, j))
33+
34+
# If cell's height smaller than the level, then it can trap the rain water
35+
if heightMap[i][j] < level:
36+
res += level - heightMap[i][j]
37+
38+
# Set the height to -1 if the cell is visited
39+
heightMap[i][j] = -1
40+
41+
return res

0 commit comments

Comments
 (0)