Pacific Atlantic Water Flow (LeetCode 417): Solution and Explanation

Medium
Array
Depth First Search
Breadth First Search
Matrix

A grid of heights represents an island. The Pacific Ocean touches the top and left edges and the Atlantic touches the bottom and right edges. Rain flows from a cell to a neighbor whose height is equal or lower. Return every cell from which water can reach both oceans.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The direct approach asks, for each cell, whether a downhill path leads to the Pacific and whether one leads to the Atlantic, using a fresh DFS each time. With m × n cells and a search that may cover the whole grid, that is O((m × n)²), and it repeats the same exploration over and over.

Flip the direction of the question. Instead of asking where water from a cell can go, ask which cells can send water to a given ocean. Water reaches the Pacific from a border cell, and it reaches that border cell from any neighbor at an equal or greater height. So start at all the Pacific border cells and walk uphill, moving only to neighbors that are at least as high as the current cell. Every cell you reach can drain into the Pacific.

Do the same from the Atlantic border to get a second set. A cell belongs in the answer exactly when it is in both sets. Each of the two floods visits every cell at most once, because a visited set stops repeated work, so the whole solution is linear in the grid size instead of quadratic.

Approach: Reverse DFS from both ocean borders

  1. Create two sets, pac and atl, for cells that can reach each ocean.
  2. Define dfs(r, c, visit, prevHeight). Stop if the cell is already in visit, out of bounds, or lower than prevHeight, since water cannot flow uphill to the previous cell.
  3. Otherwise add the cell to visit and recurse into its four neighbors, passing the current height as the new prevHeight.
  4. For every column, flood the top row into pac and the bottom row into atl.
  5. For every row, flood the left column into pac and the right column into atl.
  6. Return every cell that appears in both pac and atl.

Step-by-step example

heights = [[1,2],[4,3]]
  1. The Pacific border cells are (0,0), (0,1) and (1,0). Flooding uphill from (0,1) with height 2 reaches (1,1) with height 3, so pac contains all four cells.
  2. The Atlantic border cells are (0,1), (1,0) and (1,1). From (1,0) with height 4, both neighbors are lower, so the flood stops there.
  3. From (1,1) with height 3, neighbor (0,1) has height 2, which is lower, so it cannot be climbed from here, but (0,1) is already a border cell of the Atlantic.
  4. From (0,1) with height 2, neighbor (0,0) has height 1, which is lower, so it is never added. atl is {(0,1), (1,0), (1,1)}.
  5. The intersection gives [[0,1],[1,0],[1,1]]. Cell (0,0) is excluded because every path out of it goes uphill toward the Atlantic.

Code: Python, Java, C++

1class Solution:
2    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
3        ROWS, COLS = len(heights), len(heights[0])
4        pac, atl = set(), set()
5        
6        def dfs(r, c, visit, prevHeight):
7            if ((r, c) in visit or
8                r < 0 or c < 0 or r == ROWS or c == COLS or
9                heights[r][c] < prevHeight):
10                return
11            visit.add((r, c))
12            dfs(r + 1, c, visit, heights[r][c])
13            dfs(r - 1, c, visit, heights[r][c])
14            dfs(r, c + 1, visit, heights[r][c])
15            dfs(r, c - 1, visit, heights[r][c])
16            
17        for c in range(COLS):
18            dfs(0, c, pac, heights[0][c])
19            dfs(ROWS - 1, c, atl, heights[ROWS - 1][c])
20            
21        for r in range(ROWS):
22            dfs(r, 0, pac, heights[r][0])
23            dfs(r, COLS - 1, atl, heights[r][COLS - 1])
24            
25        res = []
26        for r in range(ROWS):
27            for c in range(COLS):
28                if (r, c) in pac and (r, c) in atl:
29                    res.append([r, c])
30        return res

Time and space complexity

Time

O(m × n)

Each flood adds a cell to its set at most once and checks four neighbors per cell, so both floods together do linear work in the number of cells. The final intersection scan is also O(m × n).

Space

O(m × n)

The two sets can each hold every cell, and the recursion stack can grow to the size of the grid along a long uphill path.

Other approaches

Multi-source BFS from each border (time O(m × n), space O(m × n))

Put all border cells of one ocean in a queue at once and expand uphill level by level, then repeat for the other ocean. It has the same logic as the DFS but avoids deep recursion on large grids.

Forward search from every cell (time O((m × n)²), space O(m × n))

For each cell, run a downhill DFS and check whether it touches both a Pacific edge and an Atlantic edge. It follows the problem statement literally but repeats the same work for every cell.

Common mistakes

  • Flowing downhill during the reverse search. When walking from the ocean inward, you must move only to cells with height greater than or equal to the current one.
  • Using strict comparison and excluding equal heights. Water flows to neighbors of equal height, so equal must be allowed.
  • Sharing one visited set for both oceans, which blocks the second flood from cells the first one reached.
  • Mixing up the borders. The Pacific is the top row and left column, and the Atlantic is the bottom row and right column.

Frequently asked questions

Why search from the oceans instead of from each cell?

Searching from each cell repeats work and costs O((m × n)²). Starting at the borders and climbing uphill finds every cell that drains to that ocean in a single pass, so two passes solve the whole problem in O(m × n).

Can water flow between cells of equal height?

Yes. Water moves to any neighbor whose height is less than or equal to the current cell, which is why the reverse search climbs to neighbors with height at least as large.

BFS or DFS for Pacific Atlantic Water Flow?

Either works with the same O(m × n) complexity. BFS from all border cells at once avoids recursion limits, while DFS is shorter to write.