Pacific Atlantic Water Flow

Medium Solved

Description

There is an m × n matrix of non-negative integers representing the height of each unit cell in a continent.

The Pacific Ocean touches the left and top edges, and the Atlantic Ocean touches the right and bottom edges.

Water can flow from a cell to another if the next cell has an equal or lower height.

Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.

Input format / Clarification:

  • Line 1: 2D matrix of heights (JSON array)

Example 1:

Input:
[
 [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:

Input:
[[1]]

Output:
[[0,0]]

Note:

Output must be printed as a JSON array of coordinate pairs. Order does not matter.

No submissions yet.

Discuss DFS vs BFS from ocean borders, visited matrices, and time complexity.

Test Cases