Pacific Atlantic Water Flow

Medium

Topics
ArrayDFSBFSMatrix

You are given an m x n grid heights representing the height of each cell on an island. The Pacific Ocean touches the left and top edges, and the Atlantic Ocean touches the right and bottom edges.

Rain water flows from a cell to a neighbour (up, down, left, or right) only if the neighbour's height is less than or equal to the current cell's height. Water can flow into an ocean from any cell adjacent to that ocean.

Return a list of coordinates [r, c] from which water can reach both oceans. Return them sorted (by row, then column) so the result is unambiguous.

Example 1

01223513234422453136714545112401234PacificAtlanticPacificAtlantic
reaches both — in the answerPacific onlyAtlantic only
Numbers are heights. Water moves to a neighbour of equal or lower height, so it leaves by whichever coast it can reach: the Pacific touches the top and left edges, the Atlantic the bottom and right. The answer is every cell that can drain to both — 7 cells here.
2D grid — one row per line.
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]]

Example 2

010PacificAtlanticPacificAtlantic
reaches both — in the answer
Input:  heights = [[1]]
Output: [[0,0]]
Explanation: The single cell touches all four edges.

Constraints

  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Searching forward from every cell to see whether it drains to both oceans is the obvious approach and it is far too slow. Invert the flow instead: start at each ocean and walk uphill (to neighbours of greater or equal height). Every cell reached that way is a cell that could have drained into that ocean. Do it twice, once per ocean, and intersect the two reachable sets. Two traversals replace m x n of them.

Approach

  1. Create two boolean grids, pac and atl, marking cells that can reach each ocean.
  2. Seed a DFS or BFS from every cell on the top row and left column for the Pacific, and from every cell on the bottom row and right column for the Atlantic.
  3. From a cell, move to a neighbour only when heights[next] >= heights[cur] — that is the drain condition read backwards. Mark each visited cell in the corresponding grid.
  4. Collect every cell marked in both grids. Emit them in row-major order so the output is deterministic.
class Solution:
    def pacificAtlantic(self, heights):
        if not heights or not heights[0]:
            return []
        m, n = len(heights), len(heights[0])
        pac = [[False] * n for _ in range(m)]
        atl = [[False] * n for _ in range(m)]

        def dfs(r, c, seen):
            seen[r][c] = True
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < m and 0 <= nc < n and not seen[nr][nc] \
                        and heights[nr][nc] >= heights[r][c]:
                    dfs(nr, nc, seen)

        for r in range(m):
            dfs(r, 0, pac)
            dfs(r, n - 1, atl)
        for c in range(n):
            dfs(0, c, pac)
            dfs(m - 1, c, atl)

        return [[r, c] for r in range(m) for c in range(n) if pac[r][c] and atl[r][c]]

Dry Run

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
answer (0,4) (1,3) (1,4) (2,2) (3,0) (3,1) (4,0)
The search runs BACKWARDS, from each ocean inland, which is the one idea to hold
onto. Flooding forward from every cell would be O((m*n)^2) and time out; seeding
from the 2(m+n) border cells and walking uphill visits each cell a constant number
of times per ocean.
Because the walk is reversed, so is the comparison: water flows downhill, so
walking inland means stepping to a neighbour that is at least as high --
`grid[ny][nx] >= grid[y][x]`. Writing `<=` is the single most common bug here and
it does not fail quietly: this grid then reports fifteen cells including (0,0),
which drains to neither ocean.
It is `>=` and not `>`. Equal heights still let water pass, and a flat plateau is
exactly where that shows: with strict `>`, cell (1,4) drops out of the answer.
Each ocean needs its OWN visited grid. Share one and the first traversal blocks
the second, so the final intersection is whatever the shared grid happened to
reach -- on this input, every cell in the matrix.
Corners legitimately seed both oceans, which is why the two floods are independent
rather than one pass with two flags.

Complexity

  • Time — O(m x n) — each cell is visited at most once per ocean.
  • Space — O(m x n) for the two visited grids plus recursion depth.

Common Pitfalls

  • Do not search forward from each cell. That is O((m x n)^2) in the worst case and will time out.
  • The comparison reverses when you walk backwards: use >=, not <=. Getting this backwards is the single most common bug.
  • >= and not > — equal heights still let water pass, and flat plateaus are exactly where the off-by-one shows up.
  • A cell can belong to both seed sets (corners do). Mark visited per-ocean, not globally, or one traversal will block the other.

Full Solution — all languages

class Solution:
    def pacificAtlantic(self, grid):
        rows, cols = len(grid), len(grid[0])
        pacific = [[False] * cols for _ in range(rows)]
        atlantic = [[False] * cols for _ in range(rows)]

        def flood(r, c, seen):
            stack = [(r, c)]
            seen[r][c] = True
            while stack:
                y, x = stack.pop()
                for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < rows and 0 <= nx < cols and not seen[ny][nx] and grid[ny][nx] >= grid[y][x]:
                        seen[ny][nx] = True
                        stack.append((ny, nx))

        for r in range(rows):
            flood(r, 0, pacific)
            flood(r, cols - 1, atlantic)
        for c in range(cols):
            flood(0, c, pacific)
            flood(rows - 1, c, atlantic)

        return [[r, c] for r in range(rows) for c in range(cols)
                if pacific[r][c] and atlantic[r][c]]
Asked at Flipkart
SensAI
Beta
Tap the mic to stop voice mode