mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-03 13:27:36 +00:00
feat(work): implement Pacific Atlantic Water Flow solution
This commit is contained in:
1 parent
f5f31ba1c3
commit
d147abe993
1 file changed
+38
-4
@@ -61,15 +61,49 @@ Atlantic oceans.
|
|||||||
|
|
||||||
Constraints:
|
Constraints:
|
||||||
|
|
||||||
• m == heights.length
|
• m == heights.length
|
||||||
|
|
||||||
• n == heights[r].length
|
• n == heights[r].length
|
||||||
|
|
||||||
• 1 <= m, n <= 200
|
• 1 <= m, n <= 200
|
||||||
|
|
||||||
• 0 <= heights[r][c] <= 10^5
|
• 0 <= heights[r][c] <= 10^5
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:
|
def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:
|
||||||
|
rows, cols = len(heights), len(heights[0])
|
||||||
|
pac, atl = set(), set()
|
||||||
|
|
||||||
|
def dfs(r, c, seen, prevHeight):
|
||||||
|
if (
|
||||||
|
(r, c) in seen
|
||||||
|
or r < 0
|
||||||
|
or c < 0
|
||||||
|
or r == rows
|
||||||
|
or c == cols
|
||||||
|
or heights[r][c] < prevHeight
|
||||||
|
):
|
||||||
|
return
|
||||||
|
seen.add((r, c))
|
||||||
|
dfs(r + 1, c, seen, heights[r][c])
|
||||||
|
dfs(r - 1, c, seen, heights[r][c])
|
||||||
|
dfs(r, c + 1, seen, heights[r][c])
|
||||||
|
dfs(r, c - 1, seen, heights[r][c])
|
||||||
|
|
||||||
|
for c in range(cols):
|
||||||
|
dfs(0, c, pac, heights[0][c])
|
||||||
|
dfs(rows - 1, c, atl, heights[rows - 1][c])
|
||||||
|
|
||||||
|
for r in range(rows):
|
||||||
|
dfs(r, 0, pac, heights[r][0])
|
||||||
|
dfs(r, cols - 1, atl, heights[r][cols - 1])
|
||||||
|
|
||||||
|
res = []
|
||||||
|
for r in range(rows):
|
||||||
|
for c in range(cols):
|
||||||
|
if (r, c) in pac and (r, c) in atl:
|
||||||
|
res.append([r, c])
|
||||||
|
|
||||||
|
return res
|
||||||
Reference in new issue
Block a user