#K62562. Pacific Atlantic Water Flow

    ID: 31559 Type: Default 1000ms 256MiB

Pacific Atlantic Water Flow

Pacific Atlantic Water Flow

You are given an \(m \times n\) matrix of integers representing the heights of cells in a 2D grid. Water can flow from a cell to any of its 4 adjacent cells (up, down, left, right) if and only if the height of the destination cell is greater than or equal to the height of the current cell (i.e. \(h_{\text{dest}} \ge h_{\text{orig}}\)). The Pacific Ocean touches the left and top edges of the grid, while the Atlantic Ocean touches the right and bottom edges. Your task is to find all coordinates \((i, j)\) from which water can flow to both the Pacific and Atlantic oceans. The output coordinates must be sorted in lexicographical order first by row index, then by column index.

Note: If the matrix is empty (i.e. no cells), output should be empty.

inputFormat

The input is provided via standard input (stdin) and has the following format:

  • The first line contains two integers \(m\) and \(n\) separated by a space, denoting the number of rows and columns of the matrix. If \(m = 0\) or \(n = 0\), the matrix is considered empty.
  • The next \(m\) lines each contain \(n\) space-separated integers, representing the grid of heights.

outputFormat

The output should be printed to standard output (stdout) and follow this format:

  • The first line contains an integer \(k\) representing the number of cells from which water can flow to both oceans.
  • The next \(k\) lines each contain two space-separated integers representing the row and column indices of such a cell.
## 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
7

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

</p>