Pacific Atlantic Water Flow

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given an m x n rectangular island heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).

The island borders two oceans:

  • The Pacific Ocean touches the island's top and left edges.
  • The Atlantic Ocean touches the island's bottom and right edges.

Water can flow from a cell to an adjacent cell (up, down, left, or right) if the adjacent cell's height is less than or equal to the current cell's height. Water can also flow to the ocean if the cell is adjacent to that ocean.

Return a list of coordinates [r, c] where water can flow to both the Pacific and Atlantic oceans. The result may be returned in any order.

Examples

Example 1:

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]]

Explanation: The cells marked can reach both oceans. For example, cell [2,2] (height 5) is a local peak — water flows left/up toward the Pacific and right/down toward the Atlantic.

Example 2:

Input: heights = [[1]]

Output: [[0,0]]

Explanation: A single cell touches both oceans, so water trivially flows to both.

Example 3:

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

Output: [[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

Explanation: The spiral pattern means the center cell (height 9) and all cells along the bottom and right edges can reach both oceans.

Constraints

  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 100000
Source: Graphs pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle