← Back to Problems

Reservoir

Reservoir

You're given an elevation map — a 2D grid of non-negative integers where each cell's value is its height. After heavy rain, water collects in the valleys. Compute the total volume of water trapped on the map.

Water flows freely off the boundary of the grid (cells on the edge cannot hold any water themselves). A cell traps water up to the lowest barrier surrounding it.

Input

Line 1: two integers rows cols (1 ≤ rows, cols ≤ 250). Next rows lines: cols space-separated non-negative integers each — the heights.

Output

A single integer: the total water volume trapped on the map.

Example

Input:

3 6
3 3 3 3 3 3
3 0 0 0 0 3
3 3 3 3 3 3

Output:

12

The interior row of zeros is fully enclosed by walls of height 3, holding 4 cells × 3 height = 12 units.

Notes

  • The 1D version of this problem (a single row of heights) has a classic solution: scan left-to-right and right-to-left, then for each cell compute min(max_left, max_right) - height. A common starting point is to apply that idea row by row to handle the 2D case.

Scoring

Your solution is evaluated against 10 test cases worth 10 points each (100 total).


LEADERBOARD

Rank Developer Score Submitted
1 🥇 mrsuyashkesharwani
100 / 100
May 22, 2026, 11:24 AM UTC
2 🥈 meetpatel-D3sTr0
100 / 100
May 22, 2026, 11:34 AM UTC
3 🥉 aniket-axy
100 / 100
May 22, 2026, 11:42 AM UTC
4 parth469
100 / 100
May 22, 2026, 11:45 AM UTC
5 shivam
100 / 100
May 22, 2026, 11:46 AM UTC
6 harshwadhwani-10
100 / 100
May 22, 2026, 11:51 AM UTC
7 HetaDobariya
100 / 100
May 22, 2026, 11:53 AM UTC
8 gAditya2208
100 / 100
May 22, 2026, 11:55 AM UTC
9 Abhishek0931
100 / 100
May 22, 2026, 11:59 AM UTC
10 Anujjj12
100 / 100
May 22, 2026, 12:14 PM UTC