|
| 1 | +# Time Complexity: O(m * n) - running DFS from each border, so worst case, we visit each cell twice. |
| 2 | +# Space Complexity: O(m * n) - using two sets to track which cells can reach each ocean and the recursion stack. |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: |
| 6 | + |
| 7 | + rows = len(heights) |
| 8 | + cols = len(heights[0]) |
| 9 | + result = [] |
| 10 | + |
| 11 | + # tracking which cells can reach each ocean |
| 12 | + pac, atl = set(), set() |
| 13 | + |
| 14 | + def dfs(r, c, visited, preHeight): |
| 15 | + # if out of bounds, already visited, or can't flow from prev height → just dip |
| 16 | + if (r < 0 or c < 0 or r == rows or c == cols or |
| 17 | + (r, c) in visited or heights[r][c] < preHeight): |
| 18 | + return |
| 19 | + |
| 20 | + # mark as visited |
| 21 | + visited.add((r, c)) |
| 22 | + |
| 23 | + # go in all 4 directions |
| 24 | + dfs(r + 1, c, visited, heights[r][c]) # down |
| 25 | + dfs(r - 1, c, visited, heights[r][c]) # up |
| 26 | + dfs(r, c + 1, visited, heights[r][c]) # right |
| 27 | + dfs(r, c - 1, visited, heights[r][c]) # left |
| 28 | + |
| 29 | + # hit up all border cells for both oceans |
| 30 | + for c in range(cols): |
| 31 | + dfs(0, c, pac, heights[0][c]) # top row (pacific) |
| 32 | + dfs(rows - 1, c, atl, heights[rows - 1][c]) # bottom row (atlantic) |
| 33 | + |
| 34 | + for r in range(rows): |
| 35 | + dfs(r, 0, pac, heights[r][0]) # leftmost col (pacific) |
| 36 | + dfs(r, cols - 1, atl, heights[r][cols - 1]) # rightmost col (atlantic) |
| 37 | + |
| 38 | + # now just check which cells are in both sets |
| 39 | + for r in range(rows): |
| 40 | + for c in range(cols): |
| 41 | + if (r, c) in pac and (r, c) in atl: |
| 42 | + result.append([r, c]) |
| 43 | + |
| 44 | + return result |
0 commit comments