Update Pacific Atlantic Water Flow.cpp #81
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
For every cell (i, j) in the matrix, it checks if water can reach the Pacific Ocean (top or left edge) AND the Atlantic Ocean (bottom or right edge) from that cell via a chain of allowed moves (downhill or flat, i.e., to neighbor cells with height ≤ current cell).
High-Level Logic:
For each cell (i, j), run two separate DFS-based checks:
canReachPacific: Can water from this cell reach the Pacific? (i.e., can you move up/left, following allowed paths, all the way to edge?)
canReachAtlantic: Can water from this cell reach the Atlantic? (i.e., can you move down/right, following allowed paths, all the way to edge?)
If both are true for this cell, you add it to your answer.
How does DFS work?
Each DFS marks visited nodes using a boolean[][] to avoid revisiting and infinite loops.
Moves in four directions are made only if the next cell is within bounds and its height is less than or equal to the current cell (water can flow down or stay level). The recursion terminates when you hit the database edge (for Pacific: i < 0 or j < 0, for Atlantic: i >= heights.length or j >= heights[0].length). Result collection:
For every cell, if both DFS calls return true, you collect that cell (i, j) into your answer list. Example:
Suppose there's a cell [i][j] with value 5. It will recurse to all its accessible neighbors with values ≤ 5, marking as visited, and check if it can reach an edge. The same is done separately for both oceans. Efficiency/Complexity:
This approach is simple and intuitive, but not the most efficient since it runs DFS from every cell, often repeating work for adjacent cells. With a grid of size n x m, the work is roughly O(n^2 * (n + m)) in the worst case.