Skip to content

Commit d37bafa

Browse files
authored
Create Pacific Atlantic Water Flow - Leetcode 417.py
1 parent 1e65763 commit d37bafa

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from collections import deque
2+
3+
class Solution:
4+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
5+
p_que = deque()
6+
p_seen = set()
7+
8+
a_que = deque()
9+
a_seen = set()
10+
11+
m, n = len(heights), len(heights[0])
12+
13+
for j in range(n):
14+
p_que.append((0, j))
15+
p_seen.add((0, j))
16+
17+
for i in range(1, m):
18+
p_que.append((i, 0))
19+
p_seen.add((i, 0))
20+
21+
for i in range(m):
22+
a_que.append((i, n - 1))
23+
a_seen.add((i, n - 1))
24+
25+
for j in range(n - 1):
26+
a_que.append((m - 1, j))
27+
a_seen.add((m - 1, j))
28+
29+
def get_coords(que, seen):
30+
coords = set()
31+
while que:
32+
i, j = que.popleft()
33+
coords.add((i, j))
34+
for i_off, j_off in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
35+
r, c = i + i_off, j + j_off
36+
if 0 <= r < m and 0 <= c < n and heights[r][c] >= heights[i][j] and (r, c) not in seen:
37+
seen.add((r, c))
38+
que.append((r, c))
39+
return coords
40+
41+
p_coords = get_coords(p_que, p_seen)
42+
a_coords = get_coords(a_que, a_seen)
43+
return list(p_coords.intersection(a_coords))

0 commit comments

Comments
 (0)