-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay2
More file actions
36 lines (29 loc) · 1.2 KB
/
Day2
File metadata and controls
36 lines (29 loc) · 1.2 KB
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
# LeetCode 407. Trapping Rain Water II
Solution:-
import heapq
from typing import List
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
if not heightMap or not heightMap[0]:
return 0
m, n = len(heightMap), len(heightMap[0])
visited = [[False] * n for _ in range(m)]
heap = []
# Step 1: Push all boundary cells 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] = True
trapped_water = 0
directions = [(1,0), (-1,0), (0,1), (0,-1)]
# Step 2: Process heap
while heap:
height, x, y = heapq.heappop(heap)
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny]:
visited[nx][ny] = True
trapped_water += max(0, height - heightMap[nx][ny])
heapq.heappush(heap, (max(height, heightMap[nx][ny]), nx, ny))
return trapped_water