Skip to content

Commit 9ae3cf9

Browse files
Solve : Pacific Atlantic Water Flow
1 parent 772e847 commit 9ae3cf9

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def pacificAtlantic(self, heights):
3+
if not heights:
4+
return []
5+
m, n = len(heights), len(heights[0])
6+
pacific = [[False] * n for _ in range(m)]
7+
atlantic = [[False] * n for _ in range(m)]
8+
def dfs(r, c, visited):
9+
visited[r][c] = True
10+
for dr, dc in [(-1,0), (1,0), (0,-1), (0,1)]:
11+
nr, nc = r + dr, c + dc
12+
if 0 <= nr < m and 0 <= nc < n and not visited[nr][nc] and heights[nr][nc] >= heights[r][c]:
13+
dfs(nr, nc, visited)
14+
for i in range(m):
15+
dfs(i, 0, pacific)
16+
dfs(i, n - 1, atlantic)
17+
for j in range(n):
18+
dfs(0, j, pacific)
19+
dfs(m - 1, j, atlantic)
20+
result = []
21+
for r in range(m):
22+
for c in range(n):
23+
if pacific[r][c] and atlantic[r][c]:
24+
result.append([r, c])
25+
return result

0 commit comments

Comments
 (0)