|
| 1 | +''' |
| 2 | +# 417. Pacific Atlantic Water Flow |
| 3 | +
|
| 4 | +## Time Complexity: O(n * m) |
| 5 | +- dfs is called for each cell in the grid, and each cell is visited once. |
| 6 | +
|
| 7 | +## Space Complexity: O(n * m) |
| 8 | +- pacific and atlantic sets store the cells that can flow to the pacific and atlantic oceans respectively. |
| 9 | +''' |
| 10 | +class Solution: |
| 11 | + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: |
| 12 | + if len(heights) == 1 and len(heights[0]) == 1: |
| 13 | + return [[0, 0]] |
| 14 | + |
| 15 | + max_row, max_col = len(heights), len(heights[0]) |
| 16 | + pacific, atlantic = set(), set() |
| 17 | + directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] |
| 18 | + |
| 19 | + def dfs(r, c, visited, prev_height): |
| 20 | + out_of_bound = r < 0 or c < 0 or r >= max_row or c >= max_col |
| 21 | + if out_of_bound: |
| 22 | + return |
| 23 | + |
| 24 | + current = heights[r][c] |
| 25 | + is_visited = (r, c) in visited |
| 26 | + is_uphill = current < prev_height |
| 27 | + if is_visited or is_uphill: |
| 28 | + return |
| 29 | + |
| 30 | + visited.add((r, c)) |
| 31 | + |
| 32 | + for dr, dc in directions: |
| 33 | + dfs(r + dr, c + dc, visited, current) |
| 34 | + |
| 35 | + for r in range(max_row): |
| 36 | + dfs(r, 0, pacific, heights[r][0]) # left |
| 37 | + dfs(r, max_col - 1, atlantic, heights[r][max_col - 1]) # right |
| 38 | + for c in range(max_col): |
| 39 | + dfs(0, c, pacific, heights[0][c]) # top |
| 40 | + dfs(max_row - 1, c, atlantic, heights[max_row - 1][c]) # bottom |
| 41 | + |
| 42 | + return list(pacific & atlantic) |
0 commit comments