Trapping Rain Water I && II
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Analysis:
We first find out the max height in the array, then we start from the leftmost bar which is considered as the wall of the container. If there is a bar whose height is less than the wall, water will be saved above that bar. We do the same operation from rightmost to the highest bar position.
public class Solution {
public int trap(int[] height) {
if (height == null || height.length <= ) return ;
int maxIndex = ;
for (int i = ; i < height.length; i++) {
if (height[i] > height[maxIndex]) {
maxIndex = i;
}
}
int leftMax = height[];
int total = ;
for (int i = ; i < maxIndex; i++) {
if (height[i] < leftMax) {
total += (leftMax - height[i]);
} else {
leftMax = height[i];
}
}
int rightMax = height[height.length - ];
for (int i = height.length - ; i > maxIndex; i--) {
if (height[i] < rightMax) {
total += (rightMax - height[i]);
} else {
rightMax = height[i];
}
}
return total;
}
}
Trapping Rain Water II
Given an m x n matrix 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:
Both m and n are 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 is trapped between the blocks. The total volume of water trapped is 4.
分析:
从四周出发,选取最低点(木桶原理),然后选取周围没有被visited的点。找到更低的点,则把当前点和低点的差值作为可以装水的量,注意,在加入新的点的时候,那个点的高度应该使用当前点的高度,这样我们就不用倒着回去找最高点了。
class Solution {
public int trapRainWater(int[][] heights) {
if (heights == null || heights.length == || heights[].length == ) return ;
PriorityQueue<Cell> queue = new PriorityQueue<>(, (cell1, cell2) -> cell1.height - cell2.height);
int row = heights.length, col = heights[].length;
boolean[][] visited = new boolean[row][col];
// add border cells to the queue.
for (int i = ; i < row; i++) {
visited[i][] = true;
visited[i][col - ] = true;
queue.offer(new Cell(i, , heights[i][]));
queue.offer(new Cell(i, col - , heights[i][col - ]));
}
for (int i = ; i < col; i++) {
visited[][i] = true;
visited[row - ][i] = true;
queue.offer(new Cell(, i, heights[][i]));
queue.offer(new Cell(row - , i, heights[row - ][i]));
}
// from the borders, pick the shortest cell visited and check its neighbors:
// if the neighbor is shorter, collect the water it can trap and update its height as its height plus the water trapped
// add all its neighbors to the queue.
int[][] dirs = new int[][]{{-, }, {, }, {, -}, {, }};
int res = ;
while (!queue.isEmpty()) {
Cell cell = queue.poll();
for (int[] dir : dirs) {
int neighbor_row = cell.row + dir[];
int neighbor_col = cell.col + dir[];
if (neighbor_row >= && neighbor_row < row && neighbor_col >= && neighbor_col < col && !visited[neighbor_row][neighbor_col]) {
visited[neighbor_row][neighbor_col] = true;
res += Math.max(, cell.height - heights[neighbor_row][neighbor_col]);
queue.offer(new Cell(neighbor_row, neighbor_col, Math.max(heights[neighbor_row][neighbor_col], cell.height)));
}
}
}
return res;
}
}
class Cell {
int row;
int col;
int height;
public Cell(int row, int col, int height) {
this.row = row;
this.col = col;
this.height = height;
}
}
Trapping Rain Water I && II的更多相关文章
- leetcode 11. Container With Most Water 、42. Trapping Rain Water 、238. Product of Array Except Self 、407. Trapping Rain Water II
11. Container With Most Water https://www.cnblogs.com/grandyang/p/4455109.html 用双指针向中间滑动,较小的高度就作为当前情 ...
- [LeetCode] Trapping Rain Water II 收集雨水之二
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- [LeetCode] 407. Trapping Rain Water II 收集雨水之二
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- [LeetCode] 407. Trapping Rain Water II 收集雨水 II
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- [LeetCode] Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- [LeetCode] 42. Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- [LintCode] Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- LeetCode:Container With Most Water,Trapping Rain Water
Container With Most Water 题目链接 Given n non-negative integers a1, a2, ..., an, where each represents ...
- LeetCode - 42. Trapping Rain Water
42. Trapping Rain Water Problem's Link ------------------------------------------------------------- ...
随机推荐
- pandas 的axis参数的理解
# pandas的axis参数怎样理解? # axis=0 或者 "index": # 如果是单行操作,就指的是某一行 # 如果是聚合操作,指的是跨行cross rows # ax ...
- VS插件CodeRush for Visual Studio发布v18.2.9|附下载
CodeRush能帮助你以极高的效率创建和维护源代码.Consume-first 申明,强大的模板,智能的选择工具,智能代码分析和创新的导航以及一个无与伦比的重构集,在它们的帮助下能够大大的提高你效率 ...
- Django【第28篇】:Django Admin的相关知识
Django Admin的相关知识 一.面向对象复习 1.类的继承 class Base(object): def __init__(self,val): self.val = val def fun ...
- JavaSE---显式锁
1.概述 1.1.jdk5之前,用于 调节共享对象访问机制 只有 synchronized.volatile: jdk5之后,提供了 显示锁:Lock.ReentrantLock...: ...
- display:line-block
1.那是因为第二个标签是inline-block,它的对齐方式是基线对齐,对齐的是第一个元素里面字的下划线,所以第二个元素的下边缘对齐的是1的下划线,只要在第二个元素里面加内容或者加个空格( )就可以 ...
- rocketmq设计
# 设计(design) 1 消息存储 消息存储是RocketMQ中最为复杂和最为重要的一部分,本节将分别从RocketMQ的消息存储整体架构.PageCache与Mmap内存映射以及RocketMQ ...
- 【GDOI2014模拟】Tree
题目 Wayne 在玩儿一个很有趣的游戏.在游戏中,Wayne 建造了N 个城市,现在他想在这些城市间修一些公路,当然并不是任意两个城市间都能修,为了道路系统的美观,一共只有M 对城市间能修公路,即有 ...
- 【python实例】判断质数:for-break-else
""" for 变量 in 容器: 遍历--break 如果执行到了break语句, 则else不会被执行 else: break语句没有被执行时, 执行else &qu ...
- Spring boot @Transactional
1.注解@Transactional 2.异常回滚 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); @Ov ...
- 最近在写一些树上的东西,先发一波LCA的吧!
不会树剖的我只有去学tarjan和倍增了,个人觉得倍增比tarjan好打一点... tarjan学习的地方 http://www.cnblogs.com/JVxie/p/4854719.html 个人 ...