All problems

Problem 277

Pacific Atlantic Water Flow

Medium · 20 pts · Matrix, Depth-First Search, Breadth-First Search

Problem

An island is described by a grid of heights. The Pacific Ocean touches its top and left edges, and the Atlantic Ocean touches its bottom and right edges. Rain water flows from a cell to a neighbouring cell (up, down, left or right) whose height is less than or equal to the current height, and from any edge cell into the ocean it touches. Count the cells from which water can reach both oceans. Search backwards from the oceans: from all Pacific edge cells, climb to neighbours that are at least as high, marking what can drain to the Pacific; do the same for the Atlantic. Count the cells marked twice.

Input

First line: R and C. Next R lines: C heights.

Output

Print the number of such cells.

Constraints

1 <= R, C <= 200; 0 <= height <= 100000

Example input

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

Example output

7

Explanation

Seven cells can drain into both oceans: the top-right corner (5), the two cells of height 4 at the right of the second row, the 5 in the centre, the 6 and 7 at the start of the fourth row, and the bottom-left corner (5).

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Surrounded Regions Next: Knight Minimum Moves