Problem · Array

Pacific Atlantic Water Flow

Learn this problem
MediumAnduril logoAndurilFULLTIMEPHONE SCREEN

Problem statement

You are given an m x n matrix heights, where heights[r][c] is the height of cell (r, c). Rainwater may flow from a cell to a four-directionally adjacent cell only when the neighboring cell's height is less than or equal to the current cell's height.

The Pacific Ocean touches the top and left edges of the matrix. The Atlantic Ocean touches the bottom and right edges. Return every coordinate from which water can flow to both oceans. Return each coordinate once in ascending row order, breaking row ties by ascending column.

Function

pacificAtlantic(heights: int[][]) → int[][]

Examples

Example 1

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]]return = [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

Each returned cell has at least one non-increasing path to the Pacific boundary and at least one to the Atlantic boundary. The coordinates are listed in deterministic row-major order.

Example 2

heights = [[1]]return = [[0,0]]

The only cell touches all four matrix edges, so it can reach both oceans.

Constraints

  • 1 <= m, n <= 200.
  • 0 <= heights[r][c] <= 100000.
  • Movement is allowed only up, down, left, or right.
  • The returned coordinates must be lexicographically ordered by row and then column.

More Anduril problems

drafts saved locally
public int[][] pacificAtlantic(int[][] heights) {
    // Write your code here.
}
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]]
expected[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
checking account