Pacific Atlantic Water Flow
Find every cell of a height grid from which rain can flow to both the Pacific and the Atlantic.
An island is drawn as a grid of m rows and n columns, and heights[r][c][r, c]
Example 1
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2
Output: [[0,0]]
The Idea
Rain on a hill runs down the slopes or across flat ground, never uphill. Example 1 is a small island of that kind: 5 rows and 5 columns of heights, with the Pacific along the top and left and the Atlantic along the bottom and right.
Follow one drop that lands on the 5 at row 2, column 2. It can run right to the 3 beside it, then on to the 1 at the right edge, and from there into the Atlantic. It can also run to the 3 just above it in row 1, then left to the 2, then to the 2 above that in row 0. That 2 lies on the top edge, so the same drop can reach the Pacific too. The 5 at row 2, column 2 is in the answer.
Checking every cell like this is a lot of walking. A drop can split in several directions at each step, and drops from neighbouring cells retrace the same slopes again and again. Is there a way to find all the cells that drain into one ocean at once?
Turn the question round. Any drop that reaches the Pacific leaves the island through a cell on the top or left edge. Read its path backwards, from the ocean inland, and every step goes to a cell at least as high as the one before. So start at the edge cells and climb: every cell a climb can reach is a cell whose rain can run back down the same way into that ocean. Look at the picture below.
The blue arrows, marked "climb from the Pacific", start at the 1 in row 0, col 0 and step up through 2, 2 and 3 to the 5 at row 2, col 2. The teal arrows, marked "climb from the Atlantic", start at the 1 in row 2, col 4 on the right edge and step up through 3 to the same 5. Both climbs reach it, so its rain can reach both oceans.
The shading shows where all the climbs end up. Blue cells, marked "reaches the Pacific only", are reached only from the Pacific, teal cells only from the Atlantic, and the seven orange cells, marked "reaches both oceans", are exactly the output of Example 1. So the whole problem comes down to two climbs, one from each ocean's edges, and the cells that both of them reach.
Solution Approach
Turning the climbs into code means settling three things: how the grid works as a graph, how one climb marks cells, and where the climbs start. Following the water down from each cell would also work, but it is slow.
Following the water down from each cell
Why not drop water on each cell and search downhill for the two oceans? One such search can visit every one of the m × n cells, and there are m × n cells to start from, so the total grows to about (m × n)2 steps. Most of that work repeats, because the searches from two neighbouring cells usually cover the same slopes. The two climbs from the edges visit each cell at most once per ocean.
The grid as a graph
What does a climb move along? Each cell is a point, and it is linked to the cells directly above, below, left and right of it. Points with links between them are what a graph is, so the island is a graph whose links are given by the grid itself. Many graph problems first build an adjacency list, a list of linked points for each point. Here no list is needed, because a cell's neighbours follow from its row and column.
The four steps are kept as row and column changes: down {1, 0}{-1, 0}{0, 1}{0, -1}
Marking cells in one climb
How does a climb remember where it has been? It keeps a grid of true or false values the same size as the island, one grid per ocean, and sets a cell to true when the climb reaches it. From a marked cell, the climb moves to each neighbour that is at least as high and not marked yet.
The climb follows one path as far up as it can, then backs up to the last cell that still has an unmarked neighbour at least as high, and tries that one. Going deep first and backing up later is called depth-first search, or DFS for short. A method that calls itself for each neighbour does this naturally, and the method here is called climb
The marks also stop endless loops on flat ground. In Example 1, the 2 at row 0, col 1 and the 2 at row 1, col 1 are neighbours of equal height, so each counts as "at least as high" as the other. Without the marks, the climb would step between them forever.
Where the climbs start
Which cells start a climb? For the Pacific, every cell in row 0 and every cell in column 0, because rain on them flows straight into that ocean. For the Atlantic, every cell in the last row and the last column. A corner such as row 0, col 4 touches both oceans and starts a climb for each.
All the climbs for one ocean share that ocean's grid of marks. A climb that runs into a cell an earlier climb already marked stops there, so each cell is marked at most once per ocean, however many edge cells could reach it.
Java Solution
The method pacificAtlantic
- First, read the number of rows into
and of columns intom , and create twon grids of that size,boolean andpacific . A cell ofatlantic becomes true once a climb from the Pacific reaches it, andpacific works the same way.atlantic - Start the climbs from the edges with two loops, one after the other. The first loop goes down the rows and, for each row
, callsr on column 0 withclimb and on columnpacific withn - 1 . The second loop goes across the columns and does the same for row 0 and rowatlantic .m - 1 - Each call
returns at once ifclimb(h, reach, r, c) is already true. Otherwise it marks the cell, then adds each step inreach[r][c] to get a neighbour atDIRS ,nr . When that neighbour is inside the grid andnc , the method calls itself on it.h[nr][nc] >= h[r][c] - Finally, two loops, one inside the other, go over every cell, and each cell marked in both grids is added to
asresult .List.of(r, c)
The mainshow
import java.util.ArrayList;
import java.util.List;
public class PacificAtlanticWaterFlow {
private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static 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];
for (int r = 0; r < m; r++) {
climb(heights, pacific, r, 0); // left edge touches the Pacific
climb(heights, atlantic, r, n - 1); // right edge touches the Atlantic
}
for (int c = 0; c < n; c++) {
climb(heights, pacific, 0, c); // top edge: Pacific
climb(heights, atlantic, m - 1, c); // bottom edge: Atlantic
}
List<List<Integer>> result = new ArrayList<>();
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (pacific[r][c] && atlantic[r][c]) {
result.add(List.of(r, c));
}
}
}
return result;
}
// Walk uphill from the ocean: every cell reached can drain down to that ocean.
private static void climb(int[][] h, boolean[][] reach, int r, int c) {
if (reach[r][c]) {
return; // already marked for this ocean
}
reach[r][c] = true;
for (int[] d : DIRS) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < h.length && nc >= 0 && nc < h[0].length
&& h[nr][nc] >= h[r][c]) { // neighbour at least as high
climb(h, reach, nr, nc);
}
}
}
// Prints the grid row by row, with * after each cell that reaches both oceans.
static void show(int[][] heights) {
List<List<Integer>> both = pacificAtlantic(heights);
for (int r = 0; r < heights.length; r++) {
StringBuilder row = new StringBuilder();
for (int c = 0; c < heights[0].length; c++) {
String mark = both.contains(List.of(r, c)) ? "*" : " ";
row.append(String.format("%3d%s", heights[r][c], mark));
}
System.out.println(row);
}
System.out.println(both);
System.out.println();
}
public static void main(String[] args) {
show(new int[][] {{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}});
show(new int[][] {{1}});
show(new int[][] {{3, 3, 3}, {3, 3, 3}}); // flat: every cell drains both ways
show(new int[][] {{5, 5, 5}, {5, 1, 5}, {5, 5, 5}}); // a pit in the middle
show(new int[][] {{1, 2, 3, 4}}); // a single row
}
}
Running it prints:
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]]
3* 3* 3*
3* 3* 3*
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]
5* 5* 5*
5* 1 5*
5* 5* 5*
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1], [2, 2]]
1* 2* 3* 4*
[[0, 0], [0, 1], [0, 2], [0, 3]]
In the first grid, the stars sit on the 5 at the end of row 0, the two 4s at the end of row 1 and the 5 in the middle of row 2. Lower down, they mark the 6 and 7 in row 3 and the 5 in row 4. The list under it is the output of Example 1. The 1 in the top left has no star: it pours into the Pacific, but no climb from the Atlantic reaches it.
The flat grid of 3s is starred everywhere, because equal heights count as "at least as high", so each climb crosses the whole plateau. The pit grid is starred everywhere except the 1 in the middle: it is lower than all four neighbours, so no climb ever steps down into it. In the single row, every cell touches the top edge and the bottom edge, so all four reach both oceans.
The direction of h[nr][nc] >= h[r][c]<=
Complexity
The work is the two climbs, each marking a cell at most once, plus one last pass over the grid.
- Time: O(m × n), because each of the two climbs marks each cell at most once and checks only its four neighbours, and the final loops read every cell once more.
- Space: O(m × n), because the two grids of marks hold 2 × m × n values, and the chain of
calls can grow m × n deep along a long staircase of rising heights.climb