Trapping Rain Water II
Question
Given n x m non-negative integers representing an elevation map 2d where the area of each cell is 1 x 1, compute how much water it is able to trap after raining.

Example
Given 5*4 matrix
return 14.
Tags
LintCode Copyright Heap Matrix
Related Problems
Medium Trapping Rain Water
Analysis
本题是Trapping Rain Water的follow up,I中是循环两遍记录每个位置左右两侧的最高水柱,而II在二维的灌水情境中,则需要从外围向内包围查找,记录最小的柱高,也就是木桶原理,最矮的柱子决定了灌水的高度。
从最外围一圈向内部遍历,记录包围“墙”的最小柱高,可以利用min-heap(PriorityQueue)
记录遍历过的点
visited[][]对于min-heap的堆顶元素,假设高度
h,查找其周围4个方向上未曾访问过的点如果比
h高,则说明不能装水,但是提高了“围墙”最低高度,因此将其加入min-heap中,设置元素被访问如果比
h矮,则说明可以向其中灌水,且灌水高度就是h - h',其中h'是当前访问的柱子高度,同样的,要将其加入min heap中,(且该元素高度记为灌水后的高度,也就是h,可以设想为一个虚拟的水位高度),设置元素被访问
此外,为了方便,可以定义一个Cell类,包含其坐标x,y,以及高度h,并定义其Comparator规则(也可以在初始化PriorityQueue的时候定义)。
Solution
Reference
Last updated
Was this helpful?