Skip to content

Commit 343edb3

Browse files
committed
[LeetCode Sync] Runtime - 132 ms (51.98%), Memory - 20.5 MB (37.70%)
1 parent c9a5f82 commit 343edb3

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg" style="width: 361px; height: 321px;" />
6+
<pre>
7+
<strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
8+
<strong>Output:</strong> 4
9+
<strong>Explanation:</strong> After the rain, water is trapped between the blocks.
10+
We have two small ponds 1 and 3 units trapped.
11+
The total volume of water trapped is 4.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg" style="width: 401px; height: 321px;" />
16+
<pre>
17+
<strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
18+
<strong>Output:</strong> 10
19+
</pre>
20+
21+
<p>&nbsp;</p>
22+
<p><strong>Constraints:</strong></p>
23+
24+
<ul>
25+
<li><code>m == heightMap.length</code></li>
26+
<li><code>n == heightMap[i].length</code></li>
27+
<li><code>1 &lt;= m, n &lt;= 200</code></li>
28+
<li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li>
29+
</ul>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def trapRainWater(self, heightMap: List[List[int]]) -> int:
3+
m, n = len(heightMap), len(heightMap[0])
4+
visited = [[False] * n for _ in range(m)]
5+
priority_queue = []
6+
7+
for i in range(m):
8+
for j in range(n):
9+
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
10+
heappush(priority_queue, (heightMap[i][j], i, j))
11+
visited[i][j] = True
12+
13+
directions = (-1, 0, 1, 0, -1)
14+
result = 0
15+
16+
while priority_queue:
17+
height, i, j = heappop(priority_queue)
18+
for dir1, dir2 in pairwise(directions):
19+
x, y = i + dir1, j + dir2
20+
if x >= 0 and x < m and y >= 0 and y < n and not visited[x][y]:
21+
result += max(0, height - heightMap[x][y])
22+
heappush(priority_queue, (max(height, heightMap[x][y]), x, y))
23+
visited[x][y] = True
24+
25+
return result

0 commit comments

Comments
 (0)