There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island’s left and top edges, and the Atlantic Ocean touches the island’s right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell’s height is less than or equal to the current cell’s height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
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]] Explanation: The following cells can flow to the Pacific and Atlantic oceans: [0,4], [1,3], [1,4], [2,2], [3,0], [3,1], [4,0]. Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
Example 2:
Input: heights = [[1]] Output: [[0,0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.
Constraints:
m == heights.lengthn == heights[r].length1 <= m, n <= 2000 <= heights[r][c] <= 10^5
Approach: Reverse BFS from Ocean Borders (Optimal Solution)
Algorithm
- Start two BFS traversals from the ocean borders — one from all cells adjacent to the Pacific (top row + left column), one from all cells adjacent to the Atlantic (bottom row + right column)
- Each BFS propagates upstream: from a cell
(x, y)to a neighbor(nx, ny)only ifheights[nx][ny] >= heights[x][y]— meaning water could flow down from the neighbor to the current cell - Mark reachable cells in
vis1(Pacific) andvis2(Atlantic) - Return all cells where both
vis1andvis2are true
Key Insight
Flowing from every cell toward the oceans would be expensive (O(m × n) cells, each exploring the whole grid). Instead, reverse the flow: start from the oceans and walk uphill. Any cell that can reach an ocean by flowing down is reachable from that ocean by walking up. Two reversed BFS runs — one per ocean — answer everything in linear time.
Time & Space Complexity
- Time Complexity: O(m × n) - every cell is visited at most once by each BFS
- Space Complexity: O(m × n) - the two visited matrices and queues
Java Implementation
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class PacificAtlanticWaterFlow {
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int m = heights.length, n = heights[0].length;
boolean[][] pacific = new boolean[m][n];
boolean[][] atlantic = new boolean[m][n];
Deque<int[]> q1 = new ArrayDeque<>();
Deque<int[]> q2 = new ArrayDeque<>();
// Borders touching each ocean
for (int i = 0; i < m; i++) {
q1.offer(new int[] {i, 0}); // Pacific: left column
pacific[i][0] = true;
q2.offer(new int[] {i, n - 1}); // Atlantic: right column
atlantic[i][n - 1] = true;
}
for (int j = 0; j < n; j++) {
q1.offer(new int[] {0, j}); // Pacific: top row
pacific[0][j] = true;
q2.offer(new int[] {m - 1, j}); // Atlantic: bottom row
atlantic[m - 1][j] = true;
}
bfs(heights, q1, pacific);
bfs(heights, q2, atlantic);
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j]) {
ans.add(List.of(i, j));
}
}
}
return ans;
}
private void bfs(int[][] heights, Deque<int[]> queue, boolean[][] visited) {
int m = heights.length, n = heights[0].length;
int[] dirs = {-1, 0, 1, 0, -1};
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int x = cell[0], y = cell[1];
for (int k = 0; k < 4; k++) {
int nx = x + dirs[k];
int ny = y + dirs[k + 1];
// Move uphill: neighbor must be at least as tall
if (nx >= 0 && nx < m && ny >= 0 && ny < n
&& !visited[nx][ny]
&& heights[nx][ny] >= heights[x][y]) {
visited[nx][ny] = true;
queue.offer(new int[] {nx, ny});
}
}
}
}
}
Example Walkthrough
For heights = [[1]]:
- Pacific BFS starts from
(0,0)and marks it - Atlantic BFS also starts from
(0,0)and marks it - The only cell is in both sets → return [[0,0]]
For the 5×5 example, the reversed BFS from the top/left border climbs all uphill paths feeding the Pacific, and the one from the bottom/right border climbs all paths feeding the Atlantic. Cells reachable by both runs are exactly the ones whose water can reach both oceans.
Alternative Approach: Reverse DFS
Replace the BFS with recursion: from each border cell, dfs visits the same uphill neighbors with the same heights[nx][ny] >= heights[x][y] condition. It produces identical results using the recursion stack instead of a queue.
Key Insights
- Reverse Thinking: Walk uphill from oceans instead of downhill from every cell
- Two Visited Matrices:
pacificandatlanticmark each ocean’s reachable cells independently - Non-decreasing Condition: Water flows from taller/equal to shorter/equal, so upstream neighbors must be at least as tall
- Intersection is the Answer: Cells reachable from both oceans are exactly the solution
The reverse BFS approach is the optimal solution, providing O(m × n) time and O(m × n) space.