407 Trapping Rain Water II

1. Question

Given anm x nmatrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.

Note: Bothmandnare less than 110. The height of each unit cell is greater than 0 and is less than 20,000.

Example:

Given the following 3x6 height map:
[
  [1,4,3,1,3,2],
  [3,2,1,3,2,4],
  [2,3,3,2,3,1]
]

Return 4.

The above image represents the elevation map[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]before the rain.

After the rain, water are trapped between the blocks. The total volume of water trapped is 4.

2. Implementation

(1) BFS

3. Time & Space Complexity

BFS: 时间复杂度O(mn), 空间复杂度O(mn)

Last updated

Was this helpful?