|
| 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 | + |
| 27 | +class Solution: |
| 28 | + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: |
| 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 ( |
| 38 | + 0 <= nx < m |
| 39 | + and 0 <= ny < n |
| 40 | + and (nx, ny) not in reachable |
| 41 | + and matrix[nx][ny] >= matrix[x][y] |
| 42 | + ): |
| 43 | + dfs(matrix, reachable, nx, ny) |
| 44 | + |
| 45 | + m, n = len(heights), len(heights[0]) |
| 46 | + pacific_reachable = set() |
| 47 | + atlantic_reachable = set() |
| 48 | + |
| 49 | + for i in range(m): |
| 50 | + dfs(heights, pacific_reachable, i, 0) |
| 51 | + dfs(heights, atlantic_reachable, i, n - 1) |
| 52 | + |
| 53 | + for j in range(n): |
| 54 | + dfs(heights, pacific_reachable, 0, j) |
| 55 | + dfs(heights, atlantic_reachable, m - 1, j) |
| 56 | + |
| 57 | + return list(pacific_reachable & atlantic_reachable) |
0 commit comments