Pacific Atlantic Water Flow
Medium · Graphs
Jump to codeIn a rectangular height grid, water may move to a horizontal or vertical neighbor of equal or lower height. Return cells that can reach both the top/left boundary and the bottom/right boundary.
Examples
Example 1
heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2
heights = [[1]]
Output: [[0,0]]
Constraints
- 1 <= heights.length, heights[r].length <= 100
- 0 <= heights[r][c] <= 1000
Need a hint?
Reverse the flow and start from each boundary.
Real graph interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Count Islands in a Grid and Track the Count as Land Cells Are AddedGoogle
- Order Tasks with Dependencies Using a Deterministic Topological SortOpenAI
- Snake Game: Minimum Moves to Reach the AppleJane Street
Solution approach
Run a multi-source traversal from the top and left edges, moving only to equal or higher neighbors. Separately do the same from the bottom and right edges. A cell reaches both oceans exactly when it belongs to both visited sets.
Complexity
O(mn) time and O(mn) space.
Python reference solution
def pacificAtlantic(heights):
if not heights or not heights[0]:
return []
rows, cols = len(heights), len(heights[0])
def reach(seeds):
seen = set(seeds)
stack = list(seen)
while stack:
row, col = stack.pop()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
r, c = row + dr, col + dc
if 0 <= r < rows and 0 <= c < cols and (r, c) not in seen and heights[r][c] >= heights[row][col]:
seen.add((r, c))
stack.append((r, c))
return seen
pacific = reach([(r, 0) for r in range(rows)] + [(0, c) for c in range(cols)])
atlantic = reach([(r, cols - 1) for r in range(rows)] + [(rows - 1, c) for c in range(cols)])
return [list(cell) for cell in sorted(pacific & atlantic)]
JavaScript solution
function pacificAtlantic(heights) {
if (!heights.length || !heights[0].length) return [];
const rows = heights.length, cols = heights[0].length;
function reach(seeds) {
const seen = Array.from({length: rows}, () => Array(cols).fill(false)), stack = [];
for (const [r, c] of seeds) {
if (!seen[r][c]) { seen[r][c] = true; stack.push([r, c]); }
}
while (stack.length) {
const [row, col] = stack.pop();
for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const r = row + dr, c = col + dc;
if (r >= 0 && r < rows && c >= 0 && c < cols && !seen[r][c]
&& heights[r][c] >= heights[row][col]) {
seen[r][c] = true; stack.push([r, c]);
}
}
}
return seen;
}
const p = [], a = [];
for (let r = 0; r < rows; r++) { p.push([r, 0]); a.push([r, cols - 1]); }
for (let c = 0; c < cols; c++) { p.push([0, c]); a.push([rows - 1, c]); }
const pacific = reach(p), atlantic = reach(a), answer = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) answer.push([r, c]);
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[][] pacificAtlantic(int[][] heights) {
if (heights.length == 0 || heights[0].length == 0) return new int[0][];
int rows = heights.length, cols = heights[0].length;
List<int[]> p = new ArrayList<>(), a = new ArrayList<>();
for (int r = 0; r < rows; r++) { p.add(new int[]{r, 0}); a.add(new int[]{r, cols - 1}); }
for (int c = 0; c < cols; c++) { p.add(new int[]{0, c}); a.add(new int[]{rows - 1, c}); }
boolean[][] pacific = reach(heights, p), atlantic = reach(heights, a);
List<int[]> answer = new ArrayList<>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) answer.add(new int[]{r, c});
}
return answer.toArray(new int[0][]);
}
private boolean[][] reach(int[][] heights, List<int[]> seeds) {
int rows = heights.length, cols = heights[0].length;
boolean[][] seen = new boolean[rows][cols];
Deque<int[]> stack = new ArrayDeque<>();
for (int[] cell : seeds) {
if (!seen[cell[0]][cell[1]]) { seen[cell[0]][cell[1]] = true; stack.push(cell); }
}
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!stack.isEmpty()) {
int[] cell = stack.pop();
for (int[] d : directions) {
int r = cell[0] + d[0], c = cell[1] + d[1];
if (r >= 0 && r < rows && c >= 0 && c < cols && !seen[r][c]
&& heights[r][c] >= heights[cell[0]][cell[1]]) {
seen[r][c] = true; stack.push(new int[]{r, c});
}
}
}
return seen;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>> &heights) {
if (heights.empty() || heights[0].empty()) return {};
int rows = heights.size(), cols = heights[0].size();
vector<pair<int, int>> p, a;
for (int r = 0; r < rows; r++) { p.push_back({r, 0}); a.push_back({r, cols - 1}); }
for (int c = 0; c < cols; c++) { p.push_back({0, c}); a.push_back({rows - 1, c}); }
auto pacific = reach(heights, p), atlantic = reach(heights, a);
vector<vector<int>> answer;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) answer.push_back({r, c});
}
return answer;
}
vector<vector<bool>> reach(vector<vector<int>>& heights, vector<pair<int, int>> seeds) {
int rows = heights.size(), cols = heights[0].size();
vector<vector<bool>> seen(rows, vector<bool>(cols));
vector<pair<int, int>> pending;
for (auto [r, c] : seeds) {
if (!seen[r][c]) { seen[r][c] = true; pending.push_back({r, c}); }
}
vector<pair<int, int>> directions{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!pending.empty()) {
auto [row, col] = pending.back(); pending.pop_back();
for (auto [dr, dc] : directions) {
int r = row + dr, c = col + dc;
if (r >= 0 && r < rows && c >= 0 && c < cols && !seen[r][c]
&& heights[r][c] >= heights[row][col]) {
seen[r][c] = true; pending.push_back({r, c});
}
}
}
return seen;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
1,
2,
2,
3,
5
],
[
3,
2,
3,
4,
4
],
[
2,
4,
5,
3,
1
],
[
6,
7,
1,
4,
5
],
[
5,
1,
1,
2,
4
]
]
][
[
0,
4
],
[
1,
3
],
[
1,
4
],
[
2,
2
],
[
3,
0
],
[
3,
1
],
[
4,
0
]
][
[
[
1
]
]
][
[
0,
0
]
][
[
[
1,
1
],
[
1,
1
]
]
][
[
0,
0
],
[
0,
1
],
[
1,
0
],
[
1,
1
]
][
[
[
1,
2
],
[
3,
4
]
]
][
[
0,
1
],
[
1,
0
],
[
1,
1
]
][
[
[
3,
3,
3
],
[
3,
1,
3
],
[
3,
3,
3
]
]
][
[
0,
0
],
[
0,
1
],
[
0,
2
],
[
1,
0
],
[
1,
2
],
[
2,
0
],
[
2,
1
],
[
2,
2
]
]Drafts are saved per language in this browser when storage is available.