Algo-Sim › Grid Graphs
Pacific Atlantic Water Flow
Medium · Grid Graphs · step through it in Java, Python and C++ on your own input
Rain flows to neighbours of equal or lower height. Return every cell whose water can reach both the Pacific (top/left edge) and the Atlantic (bottom/right edge).
Problem
An island's heights are given as a grid. The Pacific touches the top and left edges and the Atlantic the bottom and right edges. Rain flows from a cell to a neighbour (up, down, left, right) of equal or lower height. Return every cell from which water can reach both oceans.
Constraints
- 1 ≤ m, n ≤ 200
- 0 ≤ heights[i][j] ≤ 10⁵
- Search uphill from each ocean instead of downhill from every cell
Edge cases to test
- A single cell reaches both oceans
- All heights equal: every cell
- A single row
Follow-up questions
- Why search uphill from the oceans?
- One search per ocean marks every cell that can drain into it: O(mn), instead of a search from each cell.
- What does equal height mean?
- Water can flow to an equal-height neighbour, so the uphill search moves to cells that are ≥ the current one.
Solution
Java
class Solution {
private static final int[][] DIRS = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int rows = heights.length, cols = heights[0].length;
boolean[][] pacific = new boolean[rows][cols];
boolean[][] atlantic = new boolean[rows][cols];
Queue<int[]> pq = new ArrayDeque<>(), aq = new ArrayDeque<>();
for (int r = 0; r < rows; r++) {
mark(pq, pacific, r, 0);
mark(aq, atlantic, r, cols - 1);
}
for (int c = 0; c < cols; c++) {
mark(pq, pacific, 0, c);
mark(aq, atlantic, rows - 1, c);
}
bfs(heights, pq, pacific);
bfs(heights, aq, atlantic);
List<List<Integer>> result = new ArrayList<>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (pacific[r][c] && atlantic[r][c]) result.add(List.of(r, c));
}
}
return result;
}
private void mark(Queue<int[]> queue, boolean[][] seen, int r, int c) {
if (seen[r][c]) return;
seen[r][c] = true;
queue.offer(new int[] { r, c });
}
private void bfs(int[][] heights, Queue<int[]> queue, boolean[][] seen) {
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int[] d : DIRS) {
int nr = cell[0] + d[0], nc = cell[1] + d[1];
if (nr < 0 || nc < 0 || nr >= heights.length || nc >= heights[0].length) continue;
if (seen[nr][nc] || heights[nr][nc] < heights[cell[0]][cell[1]]) continue;
seen[nr][nc] = true;
queue.offer(new int[] { nr, nc });
}
}
}
}Python
from collections import deque
DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def pacific_atlantic(heights):
rows, cols = len(heights), len(heights[0])
pacific = [[False] * cols for _ in range(rows)]
atlantic = [[False] * cols for _ in range(rows)]
pq, aq = deque(), deque()
for r in range(rows):
mark(pq, pacific, r, 0)
mark(aq, atlantic, r, cols - 1)
for c in range(cols):
mark(pq, pacific, 0, c)
mark(aq, atlantic, rows - 1, c)
bfs(heights, pq, pacific)
bfs(heights, aq, atlantic)
result = []
for r in range(rows):
for c in range(cols):
if pacific[r][c] and atlantic[r][c]:
result.append([r, c])
return result
def mark(queue, seen, r, c):
if not seen[r][c]:
seen[r][c] = True
queue.append((r, c))
def bfs(heights, queue, seen):
while queue:
cr, cc = queue.popleft()
for dr, dc in DIRS:
nr, nc = cr + dr, cc + dc
if not (0 <= nr < len(heights) and 0 <= nc < len(heights[0])):
continue
if seen[nr][nc] or heights[nr][nc] < heights[cr][cc]:
continue
seen[nr][nc] = True
queue.append((nr, nc))C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
vector<vector<int>> pacificAtlantic(vector<vector<int>> &heights) {
int rows = int(heights.size()), cols = int(heights[0].size());
vector<vector<bool>> pacific = vector<vector<bool>>(rows, vector<bool>(cols));
vector<vector<bool>> atlantic = vector<vector<bool>>(rows, vector<bool>(cols));
deque<vector<int>> pq = {}, aq = {};
for (int r = 0; r < rows; r++) {
mark(pq, pacific, r, 0);
mark(aq, atlantic, r, cols - 1);
}
for (int c = 0; c < cols; c++) {
mark(pq, pacific, 0, c);
mark(aq, atlantic, rows - 1, c);
}
bfs(heights, pq, pacific);
bfs(heights, aq, atlantic);
vector<vector<int>> result = {};
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (pacific[r][c] && atlantic[r][c])
result.push_back({r, c});
}
}
return result;
}
void mark(deque<vector<int>> &queue, vector<vector<bool>> &seen, int r, int c) {
if (seen[r][c])
return;
seen[r][c] = true;
queue.push_back(vector<int>{r, c});
}
void bfs(vector<vector<int>> &heights, deque<vector<int>> &queue, vector<vector<bool>> &seen) {
while (!queue.empty()) {
vector<int> cell = queue.front();
queue.pop_front();
for (vector<int> &d : DIRS) {
int nr = cell[0] + d[0], nc = cell[1] + d[1];
if (nr < 0 || nc < 0 || nr >= int(heights.size()) || nc >= int(heights[0].size()))
continue;
if (seen[nr][nc] || heights[nr][nc] < heights[cell[0]][cell[1]])
continue;
seen[nr][nc] = true;
queue.push_back(vector<int>{nr, nc});
}
}
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Max Area of Island (Medium)
- Rotting Oranges (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Path in Binary Matrix (Medium)
- Shortest Bridge (Medium)
- Shortest Path in a Grid with Obstacles Elimination (Hard)
- Surrounded Regions (Medium)
- Path With Minimum Effort (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)
- Swim in Rising Water (Hard)