-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPacificAtlanticWaterFlow_Day78.py
More file actions
35 lines (27 loc) · 1.09 KB
/
Copy pathPacificAtlanticWaterFlow_Day78.py
File metadata and controls
35 lines (27 loc) · 1.09 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
from typing import List
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
if not heights:
return []
rows, cols = len(heights), len(heights[0])
pacific = set()
atlantic = set()
def dfs(r, c, visit, prev_height):
if ((r, c) in visit or
r < 0 or c < 0 or r >= rows or c >= cols or
heights[r][c] < prev_height):
return
visit.add((r, c))
dfs(r + 1, c, visit, heights[r][c])
dfs(r - 1, c, visit, heights[r][c])
dfs(r, c + 1, visit, heights[r][c])
dfs(r, c - 1, visit, heights[r][c])
# DFS for Pacific Ocean (top row + left col)
for c in range(cols):
dfs(0, c, pacific, heights[0][c])
dfs(rows - 1, c, atlantic, heights[rows - 1][c])
for r in range(rows):
dfs(r, 0, pacific, heights[r][0])
dfs(r, cols - 1, atlantic, heights[r][cols - 1])
result = [[r, c] for (r, c) in pacific & atlantic]
return result