 All Problems
Pacific Atlantic Water Flow
medium
array
depth-first search
breadth-first search
matrix
google
facebook

There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.

Water can flow to a neighboring cell (north, south, east, west) if the neighboring cell's height is less than or equal to the current cell's height.

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

Example 1:

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

Constraints:

  • m == heights.length, n == heights[i].length
  • 1 ≤ m, n ≤ 200
  • 0 ≤ heights[i][j] ≤ 10⁵

Input format: First line: m n. Then m lines each with n space-separated integers.

Output format: Each qualifying coordinate on its own line as "row col", sorted by row then col.

Run to check your code against the sample cases, or submit to run every case