417. Pacific Atlantic Water Flow
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Graphs
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven a grid of land heights, find every cell from which rainwater can flow to both the Pacific Ocean (top/left edges) and the Atlantic Ocean (bottom/right edges), where water flows from a cell only to equal-or-lower adjacent cells.
Approach
- Reverse BFS from each ocean's border: instead of simulating forward flow from every cell (expensive), seed two separate visited sets — one from all Pacific-border cells and one from all Atlantic-border cells — and expand inward to any neighbor whose height is greater than or equal to the current cell (reverse of actual flow).
- Why it works: a cell reachable from a border via this "uphill or flat" BFS is exactly the set of cells whose water can drain to that ocean; the intersection of the two sets is the answer.
- Multi-source BFS ensures each cell is visited at most once per ocean, keeping the whole algorithm linear in the grid size.
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
int m = heights.size(), n = heights[0].size();
// BFS from all border cells of one ocean; returns reachability grid.
auto bfs = [&](vector<pair<int,int>> seeds) -> vector<vector<bool>> {
vector<vector<bool>> reach(m, vector<bool>(n, false));
queue<pair<int,int>> q;
for (auto [r, c] : seeds) {
reach[r][c] = true;
q.push({r, c});
}
const int dr[] = {-1, 1, 0, 0};
const int dc[] = {0, 0, -1, 1};
while (!q.empty()) {
auto [r, c] = q.front(); q.pop();
for (int d = 0; d < 4; ++d) {
int nr = r + dr[d], nc = c + dc[d];
// expand if in-bounds, unvisited, and >= current height
if (nr >= 0 && nr < m && nc >= 0 && nc < n
&& !reach[nr][nc]
&& heights[nr][nc] >= heights[r][c]) {
reach[nr][nc] = true;
q.push({nr, nc});
}
}
}
return reach;
};
// Seed Pacific (top row + left col) and Atlantic (bottom row + right col)
vector<pair<int,int>> pacSeeds, atlSeeds;
for (int r = 0; r < m; ++r) {
pacSeeds.push_back({r, 0});
atlSeeds.push_back({r, n - 1});
}
for (int c = 0; c < n; ++c) {
pacSeeds.push_back({0, c});
atlSeeds.push_back({m - 1, c});
}
auto pac = bfs(pacSeeds);
auto atl = bfs(atlSeeds);
// Collect cells reachable from both oceans
vector<vector<int>> result;
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
if (pac[r][c] && atl[r][c])
result.push_back({r, c});
return result;
}
};
Time O(M * N) Space O(M * N)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
int m, n;
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};
void dfs(int x, int y, int prev_h, const vector<vector<int>>& h, vector<vector<bool>>& visited){
if(x<0 || x>=m || y<0 || y>=n || visited[x][y] || h[x][y]<prev_h){
return;
}
visited[x][y]=true;
for(int i=0; i<4; ++i){
dfs(x+dx[i], y+dy[i], h[x][y], h, visited);
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
m=heights.size();
n=heights[0].size();
vector<vector<bool>> pac(m, vector<bool>(n, false));
vector<vector<bool>> atl(m, vector<bool>(n, false));
for(int i=0; i<m; ++i){
dfs(i, 0, 0, heights, pac);
dfs(i, n-1, 0, heights, atl);
}
for(int j=0; j<n; ++j){
dfs(0, j, 0, heights, pac);
dfs(m-1, j, 0, heights, atl);
}
vector<vector<int>> res;
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(pac[i][j] && atl[i][j]){
res.push_back({i, j});
}
}
}
return res;
}
};
// Time: O(M*N)
// Space: O(M*N) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.