Pacific Atlantic Water Flow

Difficulty: Medium

You're given a grid of land heights. The Pacific Ocean touches the top row and left column; the Atlantic Ocean touches the bottom row and right column.

Water flows from a cell to a horizontal or vertical neighbor whose height is less than or equal to its own (never uphill, but flat is fine).

Return the coordinates of every cell whose water can reach both oceans.

Examples

Input: heights = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[0,2],[1,2],[2,0],[2,1],[2,2]]

Heights strictly increase toward the bottom-right, so every cell can always step up-or-left to lower ground and reach the Pacific. But the only cells that can reach the Atlantic are the ones already sitting on its border, since moving toward the bottom/right edges only ever goes uphill.

Input: heights = [[3,3],[3,3]]
Output: [[0,0],[0,1],[1,0],[1,1]]

The whole grid is flat, and flowing across equal height is allowed, so every cell can reach both oceans.

Constraints

  • 1 <= rows, cols <= 200

  • 0 <= heights[i][j] <= 10^5

Approach

Tracing every cell's path to both oceans works, but repeats the same traversal over and over. It's much cheaper to run the traversal in reverse, starting from the oceans.

Water flows to a neighbor of lower or equal height. So instead of asking "can this cell reach the Pacific?", ask "starting from the Pacific's border, which cells could flow into it?" In reverse, you move to a neighbor whose height is greater than or equal to the current one.

Run this reverse flood fill twice:

  • From every Pacific-border cell, marking what it reaches as "reaches Pacific".
  • From every Atlantic-border cell, marking what it reaches as "reaches Atlantic".

Cells marked by both can flow to both oceans.

Solutions

Brute Force - Trace a Path From Every Cell

For each cell, run a DFS that only steps to equal-or-lower neighbors and check whether it reaches a Pacific-border cell. Do the same for the Atlantic. A cell is in the result only if both checks succeed.

function pacificAtlantic(heights) {
  const rows = heights.length;
  const cols = heights[0].length;
  const result = [];

  function canReach(startR, startC, isBorder) {
    const seen = new Set();

    function dfs(r, c) {
      const key = r + "," + c;
      if (seen.has(key)) return false;
      seen.add(key);

      if (isBorder(r, c)) return true;

      const neighbors = [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]];
      for (const [nr, nc] of neighbors) {
        if (
          nr >= 0 && nr < rows && nc >= 0 && nc < cols &&
          heights[nr][nc] <= heights[r][c] &&
          dfs(nr, nc)
        ) {
          return true;
        }
      }

      return false;
    }

    return dfs(startR, startC);
  }

  const touchesPacific = (r, c) => r === 0 || c === 0;
  const touchesAtlantic = (r, c) => r === rows - 1 || c === cols - 1;

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (canReach(r, c, touchesPacific) && canReach(r, c, touchesAtlantic)) {
        result.push([r, c]);
      }
    }
  }

  return result;
}

Time: O((rows × cols)²) · Space: O(rows × cols)

Optimal - Reverse Multi-Source Flood Fill

Flood fill from every Pacific-border cell, stepping to neighbors whose height is greater than or equal to the current cell's. This marks every cell that can flow to the Pacific. Do the same from the Atlantic border. Cells marked by both fills are the answer.

function pacificAtlantic(heights) {
  const rows = heights.length;
  const cols = heights[0].length;

  const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false));
  const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false));

  function dfs(r, c, visited) {
    visited[r][c] = true;

    const neighbors = [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]];
    for (const [nr, nc] of neighbors) {
      if (
        nr >= 0 && nr < rows && nc >= 0 && nc < cols &&
        !visited[nr][nc] &&
        heights[nr][nc] >= heights[r][c]
      ) {
        dfs(nr, nc, visited);
      }
    }
  }

  for (let c = 0; c < cols; c++) {
    dfs(0, c, pacific);
    dfs(rows - 1, c, atlantic);
  }
  for (let r = 0; r < rows; r++) {
    dfs(r, 0, pacific);
    dfs(r, cols - 1, atlantic);
  }

  const result = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (pacific[r][c] && atlantic[r][c]) {
        result.push([r, c]);
      }
    }
  }

  return result;
}

Time: O(rows × cols) · Space: O(rows × cols)