Skip to content

Commit 8d3d967

Browse files
committed
pacific-atlantic-water-flow solution
1 parent 6cab591 commit 8d3d967

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from typing import List
2+
from collections import deque
3+
4+
# time O(mn), saoce O(mn)
5+
class Solution:
6+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
7+
m, n = len(heights), len(heights[0])
8+
# 방문 배열
9+
pacific = [[False] * n for _ in range(m)]
10+
atlantic = [[False] * n for _ in range(m)]
11+
12+
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
13+
14+
def bfs(r, c, visited):
15+
queue = deque([(r, c)])
16+
visited[r][c] = True
17+
18+
while queue:
19+
r, c = queue.popleft()
20+
21+
for dr, dc in directions:
22+
new_r, new_c = r + dr, c + dc
23+
if (0 <= new_r < m and 0 <= new_c < n
24+
and not visited[new_r][new_c]
25+
and heights[new_r][new_c] >= heights[r][c]):
26+
visited[new_r][new_c] = True
27+
queue.append((new_r, new_c))
28+
29+
for i in range(n):
30+
bfs(0, i, pacific)
31+
bfs(m - 1, i, atlantic)
32+
for i in range(m):
33+
bfs(i, 0, pacific)
34+
bfs(i, n - 1, atlantic)
35+
36+
result = []
37+
for i in range(m):
38+
for j in range(n):
39+
if pacific[i][j] and atlantic[i][j]:
40+
result.append([i, j])
41+
42+
return result
43+
44+
45+

0 commit comments

Comments
 (0)