Pacific Atlantic Water Flow (LeetCode 417): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create two sets,
pacandatl, for cells that can reach each ocean. - Define
dfs(r, c, visit, prevHeight). Stop if the cell is already invisit, out of bounds, or lower thanprevHeight, since water cannot flow uphill to the previous cell. - Otherwise add the cell to
visitand recurse into its four neighbors, passing the current height as the newprevHeight. - For every column, flood the top row into
pacand the bottom row intoatl. - For every row, flood the left column into
pacand the right column intoatl. - Return every cell that appears in both
pacandatl.
Step-by-step example
heights = [[1,2],[4,3]]
- 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
paccontains all four cells. - 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.
- 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.
- From (0,1) with height 2, neighbor (0,0) has height 1, which is lower, so it is never added.
atlis {(0,1), (1,0), (1,1)}. - 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 res1class Solution {
2 int[][] heights;
3 int ROWS, COLS;
4
5 public List<List<Integer>> pacificAtlantic(int[][] heights) {
6 this.heights = heights;
7 ROWS = heights.length;
8 COLS = heights[0].length;
9
10 Set<String> pac = new HashSet<>();
11 Set<String> atl = new HashSet<>();
12
13 for (int c = 0; c < COLS; c++) {
14 dfs(0, c, pac, heights[0][c]);
15 dfs(ROWS - 1, c, atl, heights[ROWS - 1][c]);
16 }
17 for (int r = 0; r < ROWS; r++) {
18 dfs(r, 0, pac, heights[r][0]);
19 dfs(r, COLS - 1, atl, heights[r][COLS - 1]);
20 }
21
22 List<List<Integer>> res = new ArrayList<>();
23 for (String key : pac) {
24 if (atl.contains(key)) {
25 String[] parts = key.split(",");
26 res.add(Arrays.asList(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])));
27 }
28 }
29 return res;
30 }
31
32 void dfs(int r, int c, Set<String> visit, int prevHeight) {
33 String key = r + "," + c;
34 if (r < 0 || c < 0 || r >= ROWS || c >= COLS || visit.contains(key) || heights[r][c] < prevHeight) return;
35 visit.add(key);
36 dfs(r + 1, c, visit, heights[r][c]);
37 dfs(r - 1, c, visit, heights[r][c]);
38 dfs(r, c + 1, visit, heights[r][c]);
39 dfs(r, c - 1, visit, heights[r][c]);
40 }
41}1class Solution {
2public:
3 int ROWS, COLS;
4
5 vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
6 ROWS = heights.size();
7 COLS = heights[0].size();
8
9 set<pair<int, int>> pac, atl;
10
11 for (int c = 0; c < COLS; c++) {
12 dfs(heights, 0, c, pac, heights[0][c]);
13 dfs(heights, ROWS - 1, c, atl, heights[ROWS - 1][c]);
14 }
15 for (int r = 0; r < ROWS; r++) {
16 dfs(heights, r, 0, pac, heights[r][0]);
17 dfs(heights, r, COLS - 1, atl, heights[r][COLS - 1]);
18 }
19
20 vector<vector<int>> res;
21 for (auto& p : pac) {
22 if (atl.count(p)) {
23 res.push_back({p.first, p.second});
24 }
25 }
26 return res;
27 }
28
29 void dfs(vector<vector<int>>& heights, int r, int c, set<pair<int, int>>& visit, int prevHeight) {
30 if (r < 0 || c < 0 || r >= ROWS || c >= COLS || visit.count({r, c}) || heights[r][c] < prevHeight) return;
31 visit.insert({r, c});
32 dfs(heights, r + 1, c, visit, heights[r][c]);
33 dfs(heights, r - 1, c, visit, heights[r][c]);
34 dfs(heights, r, c + 1, visit, heights[r][c]);
35 dfs(heights, r, c - 1, visit, heights[r][c]);
36 }
37};Time and space complexity
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).
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.