#K81052. Pacific Atlantic Water Flow

    ID: 35667 Type: Default 1000ms 256MiB

Pacific Atlantic Water Flow

Pacific Atlantic Water Flow

You are given an m x n grid of non-negative integers representing heights at each cell. Water can flow from a cell to its adjacent cells (up, down, left, right) if the adjacent cell's height is less than or equal to the current cell's height. Water can flow to the Pacific Ocean if a cell is connected to the top or left border, and to the Atlantic Ocean if a cell is connected to the bottom or right border.

Your task is to find all coordinates (i, j) from which water can flow to both oceans. The result should be printed with each coordinate on a new line in the format i j.

Note: If the grid is empty, produce no output.

Theoretical Background: Water flow is only possible to neighbors with height lower or equal to the current cell. Formally, for cell \( (i,j) \) with height \( h_{ij} \), water can flow into a neighbor \( (i',j') \) if \( h_{i'j'} \le h_{ij} \). Starting from the ocean borders and performing a depth-first search (DFS) or breadth-first search (BFS), one can compute the set of reachable cells. The intersection of cells reachable from both oceans gives the required answer.

inputFormat

The input is read from standard input (stdin) in the following format:

 m n
 row1
 row2
 ...
 rowm

Here, m and n are the number of rows and columns of the grid respectively. Each of the following m lines contains n space-separated non-negative integers representing that row of the grid.

If m is 0 (i.e. the grid is empty), no further lines are provided.

outputFormat

Output to standard output (stdout) the list of coordinates, one per line, where each coordinate is given as two space-separated integers i j representing the row and column indices (0-indexed). The coordinates are produced in the order found by scanning the grid row by row.

If no cell satisfies the condition or the grid is empty, 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>