#K83052. Pacific Atlantic Water Flow

    ID: 36111 Type: Default 1000ms 256MiB

Pacific Atlantic Water Flow

Pacific Atlantic Water Flow

You are given an m x n matrix of integers where each cell represents the height of that location in a terrain. Water can flow from a cell to any of its 4 adjacent cells (up, down, left, right) if and only if the adjacent cell's height is greater than or equal to the current cell's height.

The grid has two oceans: the Pacific Ocean touches the left and top borders, and the Atlantic Ocean touches the right and bottom borders. A cell is said to be able to flow to an ocean if there is a path from that cell to the ocean following the rule above.

Your task is to find all cells that can reach both the Pacific and Atlantic Oceans. Formally, for a cell at position \((i, j)\) with height \(h_{ij}\), water can flow from cell \((i, j)\) to a neighbor \((x, y)\) if \[ h_{xy} \geq h_{ij} \] and the cell can eventually reach the boundary of the respective ocean.

The answer should list the coordinates sorted in increasing order first by row and then by column.

inputFormat

The first line contains two integers m and n representing the dimensions of the matrix.

The next m lines each contain n space-separated integers representing the height values of each cell in the matrix.

You can assume \(m \ge 0\) and \(n \ge 0\). In case \(m = 0\) or \(n = 0\), the matrix is empty.

outputFormat

Output all coordinates (row and column indices) of cells from which water can flow to both the Pacific and Atlantic oceans. Each valid coordinate should be printed on a new line in the format:

i j

where i is the row index and j is the column index. The coordinates must be sorted in increasing order, first by row and then by column. If no cell can reach both oceans, output nothing.

## sample
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
0 4

1 3 1 4 2 2 3 0 3 1 4 0

</p>