The Pacific Atlantic Water Flow problem asks you to identify all coordinates in a matrix where water can flow to both the Pacific and Atlantic oceans. Water can only flow from a cell to its adjacent cells (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 left and top edges, while the Atlantic touches the right and bottom edges.
Instead of checking from each cell whether it can reach both oceans (which would be inefficient), we reverse the flow. We simulate water flowing from the oceans into the land, moving only to higher or equal elevation cells. We perform two BFS traversals: one starting from all Pacific-border cells and another from all Atlantic-border cells. The intersection of the visited cells from both traversals gives us the answer.
1. Initialize two sets: p_seen
and a_seen
to track cells reachable from the Pacific and Atlantic oceans respectively.
2. Use two queues to perform BFS from the Pacific (top and left edges) and Atlantic (bottom and right edges).
3. In each BFS, for every cell dequeued, check its neighbors. If a neighbor is in bounds, hasn’t been visited, and has a height greater than or equal to the current cell,
add it to the queue and mark it as reachable.
4. Once both traversals are done, take the intersection of p_seen
and a_seen
to find all cells that can reach both oceans.
This method performs BFS from the borders inward, rather than simulating flow from every internal cell. Each cell is visited at most twice—once per ocean—which gives us a time complexity of O(m × n), where m and n are the matrix dimensions. The space complexity is also O(m × n) due to the visited sets and queues.
The Pacific Atlantic Water Flow problem is a great example of graph traversal on a grid and demonstrates how to efficiently simulate physical processes like fluid flow. Similar logic can be used in topography analysis, water drainage systems, and game development where pathfinding and flow simulation are involved.
By performing two reverse BFS traversals from the ocean borders, we efficiently determine which cells allow water to reach both the Pacific and Atlantic. This problem showcases how classic algorithms like BFS can be adapted for grid-based simulations and real-world problems.