Skip to content

Commit 151ec8c

Browse files
committed
417. Pacific Atlantic Water Flow
1 parent d7e0b19 commit 151ec8c

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
417. Pacific Atlantic Water Flow
3+
https://leetcode.com/problems/pacific-atlantic-water-flow/
4+
5+
Solution:
6+
To solve this problem, we can use depth-first search (DFS) to explore all possible paths starting from each cell.
7+
We can create a helper function that takes the current cell and marks it as reachable.
8+
9+
- We can create two sets to store the cells that are reachable from the Pacific and Atlantic oceans.
10+
- We can start DFS from the cells on the borders of the Pacific and Atlantic oceans.
11+
- We can find the intersection of the two sets to get the cells that are reachable from both oceans.
12+
13+
14+
Time complexity: O(m x n)
15+
- m and n are the dimensions of the grid.
16+
- We explore all cells in the grid once.
17+
18+
Space complexity: O(m x n)
19+
- We use two sets to store the reachable cells from the Pacific and Atlantic oceans.
20+
- The maximum size of the sets is the number of cells in the grid.
21+
"""
22+
23+
24+
from typing import List
25+
26+
class Solution:
27+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
28+
29+
if not heights or not heights[0]:
30+
return []
31+
32+
def dfs(matrix, reachable, x, y):
33+
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
34+
reachable.add((x, y))
35+
for dx, dy in directions:
36+
nx, ny = x + dx, y + dy
37+
if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in reachable and matrix[nx][ny] >= matrix[x][y]:
38+
dfs(matrix, reachable, nx, ny)
39+
40+
m, n = len(heights), len(heights[0])
41+
pacific_reachable = set()
42+
atlantic_reachable = set()
43+
44+
for i in range(m):
45+
dfs(heights, pacific_reachable, i, 0)
46+
dfs(heights, atlantic_reachable, i, n - 1)
47+
48+
for j in range(n):
49+
dfs(heights, pacific_reachable, 0, j)
50+
dfs(heights, atlantic_reachable, m - 1, j)
51+
52+
return list(pacific_reachable & atlantic_reachable)

0 commit comments

Comments
 (0)