Pacific Atlantic Water Flow
Medium
Topics
You are given an m x n grid heights representing the height of each cell on an island. The Pacific Ocean touches the left and top edges, and the Atlantic Ocean touches the right and bottom edges.
Rain water flows from a cell to a neighbour (up, down, left, or right) only if the neighbour's height is less than or equal to the current cell's height. Water can flow into an ocean from any cell adjacent to that ocean.
Return a list of coordinates [r, c] from which water can reach both oceans. Return them sorted (by row, then column) so the result is unambiguous.
Example 1
Input: 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
Input: heights = [[1]] Output: [[0,0]] Explanation: The single cell touches all four edges.
Constraints
- m == heights.length
- n == heights[r].length
- 1 <= m, n <= 200
- 0 <= heights[r][c] <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Searching forward from every cell to see whether it drains to both oceans is the obvious approach and it is far too slow. Invert the flow instead: start at each ocean and walk uphill (to neighbours of greater or equal height). Every cell reached that way is a cell that could have drained into that ocean. Do it twice, once per ocean, and intersect the two reachable sets. Two traversals replace m x n of them.
Approach
- Create two boolean grids,
pacandatl, marking cells that can reach each ocean. - Seed a DFS or BFS from every cell on the top row and left column for the Pacific, and from every cell on the bottom row and right column for the Atlantic.
- From a cell, move to a neighbour only when
heights[next] >= heights[cur]— that is the drain condition read backwards. Mark each visited cell in the corresponding grid. - Collect every cell marked in both grids. Emit them in row-major order so the output is deterministic.
class Solution:
def pacificAtlantic(self, heights):
if not heights or not heights[0]:
return []
m, n = len(heights), len(heights[0])
pac = [[False] * n for _ in range(m)]
atl = [[False] * n for _ in range(m)]
def dfs(r, c, seen):
seen[r][c] = True
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and not seen[nr][nc] \
and heights[nr][nc] >= heights[r][c]:
dfs(nr, nc, seen)
for r in range(m):
dfs(r, 0, pac)
dfs(r, n - 1, atl)
for c in range(n):
dfs(0, c, pac)
dfs(m - 1, c, atl)
return [[r, c] for r in range(m) for c in range(n) if pac[r][c] and atl[r][c]]Dry Run
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
answer (0,4) (1,3) (1,4) (2,2) (3,0) (3,1) (4,0)
The search runs BACKWARDS, from each ocean inland, which is the one idea to hold
onto. Flooding forward from every cell would be O((m*n)^2) and time out; seeding
from the 2(m+n) border cells and walking uphill visits each cell a constant number
of times per ocean.
Because the walk is reversed, so is the comparison: water flows downhill, so
walking inland means stepping to a neighbour that is at least as high --
`grid[ny][nx] >= grid[y][x]`. Writing `<=` is the single most common bug here and
it does not fail quietly: this grid then reports fifteen cells including (0,0),
which drains to neither ocean.
It is `>=` and not `>`. Equal heights still let water pass, and a flat plateau is
exactly where that shows: with strict `>`, cell (1,4) drops out of the answer.
Each ocean needs its OWN visited grid. Share one and the first traversal blocks
the second, so the final intersection is whatever the shared grid happened to
reach -- on this input, every cell in the matrix.
Corners legitimately seed both oceans, which is why the two floods are independent
rather than one pass with two flags.Complexity
- Time — O(m x n) — each cell is visited at most once per ocean.
- Space — O(m x n) for the two visited grids plus recursion depth.
Common Pitfalls
- Do not search forward from each cell. That is O((m x n)^2) in the worst case and will time out.
- The comparison reverses when you walk backwards: use
>=, not<=. Getting this backwards is the single most common bug. >=and not>— equal heights still let water pass, and flat plateaus are exactly where the off-by-one shows up.- A cell can belong to both seed sets (corners do). Mark visited per-ocean, not globally, or one traversal will block the other.
Full Solution — all languages
class Solution:
def pacificAtlantic(self, grid):
rows, cols = len(grid), len(grid[0])
pacific = [[False] * cols for _ in range(rows)]
atlantic = [[False] * cols for _ in range(rows)]
def flood(r, c, seen):
stack = [(r, c)]
seen[r][c] = True
while stack:
y, x = stack.pop()
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols and not seen[ny][nx] and grid[ny][nx] >= grid[y][x]:
seen[ny][nx] = True
stack.append((ny, nx))
for r in range(rows):
flood(r, 0, pacific)
flood(r, cols - 1, atlantic)
for c in range(cols):
flood(0, c, pacific)
flood(rows - 1, c, atlantic)
return [[r, c] for r in range(rows) for c in range(cols)
if pacific[r][c] and atlantic[r][c]]import java.util.*;
class Solution {
public int[][] pacificAtlantic(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
boolean[][] pacific = new boolean[rows][cols];
boolean[][] atlantic = new boolean[rows][cols];
for (int r = 0; r < rows; r++) {
flood(grid, r, 0, pacific);
flood(grid, r, cols - 1, atlantic);
}
for (int c = 0; c < cols; c++) {
flood(grid, 0, c, pacific);
flood(grid, rows - 1, c, atlantic);
}
List<int[]> out = new ArrayList<>();
for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) out.add(new int[]{r, c});
return out.toArray(new int[0][]);
}
private void flood(int[][] grid, int r, int c, boolean[][] seen) {
int rows = grid.length, cols = grid[0].length;
int[][] D = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{r, c});
seen[r][c] = true;
while (!stack.isEmpty()) {
int[] cur = stack.pop();
for (int[] d : D) {
int ny = cur[0] + d[0], nx = cur[1] + d[1];
if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
if (seen[ny][nx] || grid[ny][nx] < grid[cur[0]][cur[1]]) continue;
seen[ny][nx] = true;
stack.push(new int[]{ny, nx});
}
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size();
vector<vector<char>> pacific(rows, vector<char>(cols, 0));
vector<vector<char>> atlantic(rows, vector<char>(cols, 0));
int D[4][2] = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
auto flood = [&](int r, int c, vector<vector<char>>& seen) {
vector<pair<int, int>> stack {
{
r, c
}
};
seen[r][c] = 1;
while (!stack.empty()) {
pair<int, int> cur = stack.back();
stack.pop_back();
for (auto& d : D) {
int ny = cur.first + d[0], nx = cur.second + d[1];
if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
if (seen[ny][nx] || grid[ny][nx] < grid[cur.first][cur.second]) continue;
seen[ny][nx] = 1;
stack.push_back({ny, nx});
}
}
};
for (int r = 0; r < rows; r++) {
flood(r, 0, pacific);
flood(r, cols - 1, atlantic);
}
for (int c = 0; c < cols; c++) {
flood(0, c, pacific);
flood(rows - 1, c, atlantic);
}
vector<vector<int>> out;
for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) out.push_back({r, c});
return out;
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var pacificAtlantic = function(grid) {
const rows = grid.length, cols = grid[0].length;
const make = () => Array.from({ length: rows }, () => new Array(cols).fill(false));
const pacific = make(), atlantic = make();
const flood = (r, c, seen) => {
const stack = [[r, c]];
seen[r][c] = true;
while (stack.length) {
const cur = stack.pop();
for (const d of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const ny = cur[0] + d[0], nx = cur[1] + d[1];
if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
if (seen[ny][nx] || grid[ny][nx] < grid[cur[0]][cur[1]]) continue;
seen[ny][nx] = true;
stack.push([ny, nx]);
}
}
};
for (let r = 0; r < rows; r++) {
flood(r, 0, pacific);
flood(r, cols - 1, atlantic);
}
for (let c = 0; c < cols; c++) {
flood(0, c, pacific);
flood(rows - 1, c, atlantic);
}
const out = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) out.push([r, c]);
}
return out;
};