#C4186. Ocean Flow
Ocean Flow
Ocean Flow
You are given a 2D grid of integers representing the heights of cells in a terrain. Water can flow from a cell to its neighboring cell (up, down, left, or right) if and only if the neighbor's height is less than or equal to the current cell's height.
The grid is surrounded by two oceans: the Pacific Ocean touches the left and top edges, and the Atlantic Ocean touches the right and bottom edges. Your task is to determine the number of cells from which water can flow to both the Pacific and Atlantic oceans.
For example, consider the following grid:
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
In this grid, there are 7
such cells. Formally, let M be the number of rows and N the number of columns. For every cell (i,j), water can flow to a neighboring cell (x,y) if and only if
[ \text{height}(x,y) \leq \text{height}(i,j) ]
and using this rule recursively, you need to count how many cells have a path to both oceans.
inputFormat
The input is read from stdin and has the following format:
- The first line contains two integers M and N representing the number of rows and columns respectively. If M = 0 or N = 0, the grid is empty.
- The next M lines each contain N space-separated integers representing the heights of the cells.
outputFormat
Output a single integer to stdout: the number of cells from which water can flow to both the Pacific and Atlantic oceans.
## 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
7