|
| 1 | +# m is number of rows and n is number of columns |
| 2 | +# TC : O(m*n) |
| 3 | +# SC : O(m*n) |
| 4 | +class Solution: |
| 5 | + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: |
| 6 | + ROWS, COLS = len(heights), len(heights[0]) |
| 7 | + DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)] |
| 8 | + pacific, atlantic = set(), set() |
| 9 | + result: List[List[int]] = [] |
| 10 | + |
| 11 | + def dfs( |
| 12 | + r: int, c: int, ocean_set: Set[Tuple[int, int]], prev_height: int |
| 13 | + ) -> None: |
| 14 | + if ( |
| 15 | + r < 0 |
| 16 | + or r >= ROWS |
| 17 | + or c < 0 |
| 18 | + or c >= COLS |
| 19 | + or (r, c) in ocean_set |
| 20 | + or heights[r][c] < prev_height |
| 21 | + ): |
| 22 | + return |
| 23 | + |
| 24 | + ocean_set.add((r, c)) |
| 25 | + |
| 26 | + for dr, dc in DIRECTIONS: |
| 27 | + dfs(r + dr, c + dc, ocean_set, heights[r][c]) |
| 28 | + |
| 29 | + # Water Flow Simulation from Pacific (Top and Left borders) |
| 30 | + for col in range(COLS): |
| 31 | + dfs(0, col, pacific, heights[0][col]) |
| 32 | + dfs(ROWS - 1, col, atlantic, heights[ROWS - 1][col]) |
| 33 | + |
| 34 | + for row in range(ROWS): |
| 35 | + dfs(row, 0, pacific, heights[row][0]) |
| 36 | + dfs(row, COLS - 1, atlantic, heights[row][COLS - 1]) |
| 37 | + |
| 38 | + # Finding cells reachable by both Pacific and Atlantic |
| 39 | + for r in range(ROWS): |
| 40 | + for c in range(COLS): |
| 41 | + if (r, c) in pacific and (r, c) in atlantic: |
| 42 | + result.append([r, c]) |
| 43 | + |
| 44 | + return result |
0 commit comments