#C9711. Pacific Atlantic Water Flow
Pacific Atlantic Water Flow
Pacific Atlantic Water Flow
You are given an m x n grid matrix of non-negative integers representing the height of each unit cell in a continent. The "Pacific Ocean" touches the left and top edges of the matrix and the "Atlantic Ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with an equal or lower height. Find all cells from which water can flow to both the Pacific and Atlantic oceans.
Formally, a cell (i, j) is said to hold bi-ocean flow if there exists a path of neighboring cells (moving only in the four cardinal directions) starting from (i, j) and reaching any cell on the Pacific border, and another (possibly different) path reaching any cell on the Atlantic border.
Hint: Use depth-first search (DFS) from the ocean borders and work your way inward. Note that for any cell, water can flow from cell (i, j) to cell (k, l) if and only if
inputFormat
The input is provided on stdin in the following format:
<number of rows> <number of columns> <row 0 values separated by spaces> <row 1 values separated by spaces> ... <row m-1 values separated by spaces>
If the number of rows is zero, the matrix is empty.
outputFormat
Output to stdout a list of coordinate pairs in the following format:
[[i1, j1], [i2, j2], ..., [ik, jk]]
The coordinate pairs should be sorted in ascending order first by row index and then by column index.
## sample5 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
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]