Skip to content

Commit 22e8dd8

Browse files
committed
- Pacific Atlantic Water Flow #260
1 parent 080179d commit 22e8dd8

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from typing import List
2+
from collections import deque
3+
4+
class Solution:
5+
"""
6+
- Time Complexity: O(mn)
7+
- Space Complexity: O(mn)
8+
"""
9+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
10+
m, n = len(heights), len(heights[0])
11+
12+
# Visit checking for each ocean
13+
p_visited = [[False] * n for _ in range(m)]
14+
a_visited = [[False] * n for _ in range(m)]
15+
16+
def bfs(q, visited):
17+
dir = [(-1, 0), (0, -1), (1, 0), (0, 1)]
18+
while q:
19+
r, c = q.popleft()
20+
for dx, dy in dir:
21+
next_r, next_c = r + dx, c + dy
22+
# checking next cell is not visited and higher than current cell
23+
if ( 0 <= next_r < m and 0 <= next_c < n and not visited[next_r][next_c]
24+
and heights[next_r][next_c] >= heights[r][c] ):
25+
visited[next_r][next_c] = True
26+
q.append((next_r, next_c))
27+
28+
p_dq, a_dq = deque(), deque()
29+
30+
for i in range(m):
31+
# left side (pacific)
32+
p_dq.append((i, 0))
33+
p_visited[i][0] = True
34+
# right side (atlantic)
35+
a_dq.append((i, n - 1))
36+
a_visited[i][n - 1] = True
37+
38+
for j in range(n):
39+
# top side (pacific)
40+
p_dq.append((0, j))
41+
p_visited[0][j] = True
42+
# bottom side (atlantic)
43+
a_dq.append((m - 1, j))
44+
a_visited[m - 1][j] = True
45+
46+
bfs(p_dq, p_visited)
47+
bfs(a_dq, a_visited)
48+
49+
result = []
50+
for i in range(m):
51+
for j in range(n):
52+
if p_visited[i][j] and a_visited[i][j]:
53+
# both of oceans are accessible
54+
result.append([i, j])
55+
56+
return result
57+
58+
tc = [
59+
([[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]], [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]),
60+
([[1]], [[0,0]])
61+
]
62+
63+
sol = Solution()
64+
for i, (h, e) in enumerate(tc, 1):
65+
r = sol.pacificAtlantic(h)
66+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)