417. Pacific Atlantic Water Flow
Asked at 12Amazon46Google42Microsoft25Apple22Meta22Bloomberg14Urban Company100Nutanix60ServiceNow55Flipkart52TikTok50Adobe44
Problem
heights is an island's height map. The Pacific touches its top and left edges, the Atlantic its bottom and right edges. Rain flows from a cell to a neighbour (up, down, left, right) of equal or lower height, and from edge cells into the adjacent ocean. Return every cell from which water can reach both oceans.
Example: [[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]]
Constraints: up to 200 × 200.
Reverse the flow: from each ocean's border, walk uphill (to neighbours ≥ current). Cells reachable from both oceans are the answer.
Complexity: O(R·C).
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
R, C = len(heights), len(heights[0])
def reach(starts):
seen, st = set(starts), list(starts)
while st:
r, c = st.pop()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if (0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen
and heights[nr][nc] >= heights[r][c]):
seen.add((nr, nc))
st.append((nr, nc))
return seen
pac = reach([(0, c) for c in range(C)] + [(r, 0) for r in range(R)])
atl = reach([(R - 1, c) for c in range(C)] + [(r, C - 1) for r in range(R)])
return sorted([r, c] for r, c in pac & atl)
H = [[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]]
assert sorted(Solution().pacificAtlantic(H)) == sorted([[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]])
assert Solution().pacificAtlantic([[1]]) == [[0, 0]]
assert sorted(Solution().pacificAtlantic([[2, 1], [1, 2]])) == [[0, 0], [0, 1], [1, 0], [1, 1]]
class Solution {
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int R = heights.length, C = heights[0].length;
boolean[][] pac = new boolean[R][C], atl = new boolean[R][C];
for (int r = 0; r < R; r++) { dfs(heights, r, 0, pac); dfs(heights, r, C - 1, atl); }
for (int c = 0; c < C; c++) { dfs(heights, 0, c, pac); dfs(heights, R - 1, c, atl); }
List<List<Integer>> res = new ArrayList<>();
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++)
if (pac[r][c] && atl[r][c]) res.add(List.of(r, c));
return res;
}
private void dfs(int[][] h, int r, int c, boolean[][] seen) {
if (seen[r][c]) return;
seen[r][c] = true;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nc >= 0 && nr < h.length && nc < h[0].length && h[nr][nc] >= h[r][c]) dfs(h, nr, nc, seen);
}
}
}
func pacificAtlantic(heights [][]int) [][]int {
R, C := len(heights), len(heights[0])
reach := func(starts [][2]int) [][]bool { // cells that can flow into this ocean (walk uphill from it)
seen := make([][]bool, R)
for i := range seen {
seen[i] = make([]bool, C)
}
st := starts
for _, p := range starts {
seen[p[0]][p[1]] = true
}
for len(st) > 0 {
p := st[len(st)-1]
st = st[:len(st)-1]
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr >= 0 && nr < R && nc >= 0 && nc < C && !seen[nr][nc] && heights[nr][nc] >= heights[p[0]][p[1]] {
seen[nr][nc] = true
st = append(st, [2]int{nr, nc})
}
}
}
return seen
}
var pacStart, atlStart [][2]int
for c := 0; c < C; c++ {
pacStart = append(pacStart, [2]int{0, c})
atlStart = append(atlStart, [2]int{R - 1, c})
}
for r := 0; r < R; r++ {
pacStart = append(pacStart, [2]int{r, 0})
atlStart = append(atlStart, [2]int{r, C - 1})
}
pac, atl := reach(pacStart), reach(atlStart)
res := [][]int{}
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
if pac[r][c] && atl[r][c] {
res = append(res, []int{r, c})
}
}
}
return res
}