medium +20 pts

Pacific Atlantic Matrix DFS

Find all cells that can flow to both oceans via DFS.

You are given an m x n matrix of non-negative integers `heights`, where each entry represents the height of a cell. Rain water can flow from a cell to its four directional neighbors (north, south, east, west) if the neighbor's height is less than or equal to the current cell's height. Imagine the matrix is surrounded by two oceans: the Pacific Ocean touches the top and left edges, and the Atlantic Ocean touches the bottom and right edges. Implement the function `pacific_atlantic(heights: List[List[int]]) -> List[List[int]]` that returns a list of coordinates `[r, c]` (in any order) where water can flow from that cell to both the Pacific and Atlantic oceans. Constraints: - 1 <= m, n <= 200 - 0 <= heights[i][j] <= 10^5 - Return coordinates as a list of lists of two integers. The order of coordinates does not matter, but each coordinate must appear exactly once.

Constraints

1 <= m, n <= 200; 0 <= heights[i][j] <= 10^5

Example

```python
# Example 1
heights = [
    [1,2,2,3,5],
    [3,2,3,4,4],
    [2,4,5,3,1],
    [6,7,1,4,5],
    [5,1,1,2,4]
]
pacific_atlantic(heights)
# Output (order may vary): [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

# Example 2
heights = [[1]]
pacific_atlantic(heights)
# Output: [[0,0]]
```
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about reverse flow: start from ocean edges and move inward to higher or equal heights.
Use two boolean matrices to track which cells can reach Pacific and which can reach Atlantic.
DFS from the top/left edges for Pacific and bottom/right edges for Atlantic separately.
Combine the two reachable sets at the end.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.