|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: |
| 6 | + # If the input is empty, return an empty list |
| 7 | + if not heights: |
| 8 | + return [] |
| 9 | + |
| 10 | + # Get the number of rows and columns in the grid |
| 11 | + row_length, col_length = len(heights), len(heights[0]) |
| 12 | + |
| 13 | + # Initialize 2D arrays to track cells reachable by Pacific and Atlantic oceans |
| 14 | + pacific_reachable = [ |
| 15 | + [False for _ in range(col_length)] for _ in range(row_length) |
| 16 | + ] |
| 17 | + atlantic_reachable = [ |
| 18 | + [False for _ in range(col_length)] for _ in range(row_length) |
| 19 | + ] |
| 20 | + |
| 21 | + # Define a depth-first search (DFS) function |
| 22 | + def dfs(row, col, reachable, prev_height): |
| 23 | + # Terminate if the cell is out of bounds, already visited, or has a lower height |
| 24 | + if ( |
| 25 | + row < 0 |
| 26 | + or col < 0 |
| 27 | + or row >= row_length |
| 28 | + or col >= col_length |
| 29 | + or reachable[row][col] |
| 30 | + or heights[row][col] < prev_height |
| 31 | + ): |
| 32 | + return |
| 33 | + |
| 34 | + # Mark the current cell as reachable |
| 35 | + reachable[row][col] = True |
| 36 | + |
| 37 | + # Perform DFS in all four directions |
| 38 | + for delta_row, delta_column in [(1, 0), (-1, 0), (0, 1), (0, -1)]: |
| 39 | + dfs(row + delta_row, col + delta_column, reachable, heights[row][col]) |
| 40 | + |
| 41 | + # Start DFS from the edges of the grid that are adjacent to the Pacific and Atlantic oceans |
| 42 | + for i in range(row_length): |
| 43 | + dfs(i, 0, pacific_reachable, heights[i][0]) # Pacific side |
| 44 | + dfs( |
| 45 | + i, col_length - 1, atlantic_reachable, heights[i][col_length - 1] |
| 46 | + ) # Atlantic side |
| 47 | + |
| 48 | + for j in range(col_length): |
| 49 | + dfs(0, j, pacific_reachable, heights[0][j]) # Pacific top |
| 50 | + dfs( |
| 51 | + row_length - 1, j, atlantic_reachable, heights[row_length - 1][j] |
| 52 | + ) # Atlantic bottom |
| 53 | + |
| 54 | + result = [] |
| 55 | + |
| 56 | + # Collect cells that can reach both the Pacific and Atlantic oceans |
| 57 | + for r in range(row_length): |
| 58 | + for c in range(col_length): |
| 59 | + if pacific_reachable[r][c] and atlantic_reachable[r][c]: |
| 60 | + result.append([r, c]) |
| 61 | + |
| 62 | + return result |
0 commit comments