Problem Description
Given an m x n matrix representing heights of cells on an island, determine which cells can allow water to flow to both the Pacific and Atlantic oceans. The Pacific touches the left and top borders, while the Atlantic touches the right and bottom borders. Water can flow from a cell to its four neighbors if the neighbor’s height is less than or equal to the current cell's height.
Key Insights
- Reverse the typical DFS/BFS perspective: start from the oceans and work inward.
- Maintain two matrices (or sets) to keep track of cells reachable from the Pacific and Atlantic edges.
- A cell can be added to the result if it is reached in both traversals.
- The height constraint ensures water flows only in non-increasing order.
Space and Time Complexity
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Each cell is processed up to twice (once from each ocean). Space Complexity: O(m * n) for the visited matrices and the recursion/queue used in DFS/BFS.
Solution
The solution uses depth-first search (DFS) from the ocean boundaries. We initialize two boolean matrices, one for each ocean. For the Pacific, we start DFS from the leftmost column and top row; for the Atlantic, we start from the rightmost column and bottom row. In each DFS, if the next cell has a height equal to or greater than the current cell and hasn’t been visited, we continue the search. Finally, we scan through the grid to collect cells that are reachable from both oceans. This reverse search simplifies the path validations and leverages the allowed water flow conditions.