Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8abbce3

Browse files
committed
feat: add solution for pacific and atlantic water flow
1 parent 52c2a84 commit 8abbce3

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List
2+
3+
def pacificAtlantic(heights: List[List[int]]) -> List[List[int]]:
4+
res = []
5+
if not heights:
6+
return res
7+
8+
ROWS, COLS = len(heights), len(heights[0])
9+
pac, atl = set(), set()
10+
11+
def dfs(r, c, visit, preHeight):
12+
if (r,c) in visit or r < 0 or c < 0 or r == ROWS or c == COLS or preHeight > heights[r][c]:
13+
return
14+
visit.add((r,c))
15+
dfs(r - 1, c, visit, heights[r][c])
16+
dfs(r + 1, c, visit, heights[r][c])
17+
dfs(r, c - 1, visit, heights[r][c])
18+
dfs(r, c + 1, visit, heights[r][c])
19+
20+
for c in range(COLS):
21+
dfs(0, c, pac, heights[0][c])
22+
dfs(ROWS - 1, c, atl, heights[ROWS - 1][c])
23+
24+
for r in range(ROWS):
25+
dfs(r, 0, pac, heights[r][0])
26+
dfs(r, COLS - 1, atl, heights[r][COLS -1])
27+
28+
for r in range(ROWS):
29+
for c in range(COLS):
30+
if (r, c) in pac and (r, c) in atl:
31+
res.append([r, c])
32+
33+
return res
34+
35+
assert pacificAtlantic([[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]]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /