All problems

Problem 600

Trapping Rain Water II

Hard · 30 pts · Matrix, Heap, Breadth-First Search

Problem

An R × C grid gives the height of each unit cell of a terrain. After heavy rain, water collects in cells that are surrounded by higher walls; water flows off the edges of the grid. Compute the total volume of trapped water. Start with all border cells in a min-heap. Repeatedly take the lowest boundary cell: each unvisited neighbour can hold water up to that boundary level, and it joins the boundary at height max(its own height, that level).

Input

The first line contains R and C. Each of the next R lines contains C integers.

Output

Print the total volume of trapped water.

Constraints

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

Example input

3 6
1 4 3 1 3 2
3 2 1 3 2 4
2 3 3 2 3 1

Example output

4

Explanation

In the grid 1 4 3 1 3 2 / 3 2 1 3 2 4 / 2 3 3 2 3 1, the neighbouring cells of height 2 and 1 in the middle row fill up to level 3, holding 1 and 2 units, and the cell of height 2 further right holds 1 unit. The total is 4.

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

Previous: Single-Threaded CPU Next: Sum of Nodes with Even-Valued Grandparent