medium +25 pts

Pacific Atlantic Flow

Find all cells that can drain to both oceans using multi-source BFS.

You are given an `m x n` matrix `heights` where `heights[r][c]` is the height of the cell at row `r` and column `c`. Water can flow from a cell to any of its four neighbors (up, down, left, right) if the neighbor's height is **less than or equal to** the current cell's height. The Pacific Ocean touches the **top and left** edges, while the Atlantic Ocean touches the **bottom and right** edges. Write a function `pacific_atlantic(heights: list[list[int]]) -> list[list[int]]` that returns a list of `[r, c]` pairs for **all** cells from which water can flow to **both** the Pacific and Atlantic oceans. The order of the returned cells does not matter. **Constraints:** - `1 <= m, n <= 200` - `0 <= heights[r][c] <= 10^5` You may assume that the input matrix is always valid and non-empty.

Constraints

1 <= m, n <= 200; 0 <= heights[r][c] <= 10^5. The solution should handle up to 40,000 cells. A BFS/DFS from the ocean borders that runs in O(m*n) is expected.

Example

>>> pacific_atlantic([[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]])
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

>>> pacific_atlantic([[1]])
[[0,0]]
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about the problem in reverse: instead of tracking water flow from each cell, start from the ocean borders and move inward to higher or equal heights.
Use two boolean grids (or sets) to mark cells reachable from the Pacific and from the Atlantic separately.
Perform a BFS or DFS from all Pacific-border cells and from all Atlantic-border cells simultaneously.
The answer is the set of cells marked in both boolean grids.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.