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的更多相关文章

  1. 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 用双指针向中间滑动,较小的高度就作为当前情 ...

  2. [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 ...

  3. [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 ...

  4. [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 ...

  5. [LeetCode] Trapping Rain Water 收集雨水

    Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...

  6. [LeetCode] 42. Trapping Rain Water 收集雨水

    Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...

  7. [LintCode] Trapping Rain Water 收集雨水

    Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...

  8. LeetCode:Container With Most Water,Trapping Rain Water

    Container With Most Water 题目链接 Given n non-negative integers a1, a2, ..., an, where each represents ...

  9. LeetCode - 42. Trapping Rain Water

    42. Trapping Rain Water Problem's Link ------------------------------------------------------------- ...

随机推荐

  1. ocvate常用函数

    1.生成矩阵相关 https://www.coursera.org/learn/machine-learning/lecture/9fHfl/basic-operations 1. 初始化矩阵 a = ...

  2. vim比较文件

    横向分割显示: $ vim -o filename1 filename2 纵向分割显示: $ vim -O filename1 filename2 ctl w w 切换文件

  3. python 导入模块、包

    1. 模块:一个有逻辑的python文件,包含变量.函数.类等.2. 包:一个包含__init__.py的文件夹,存放多个模块 import 本质是路径搜索,查找sys.path下有无你导入的 pac ...

  4. Netty学习--第二章 BIO的模型详解

    一.什么是阻塞.非阻塞.同步.异步 我们以A线程调用B线程的过程例子来讲解这四个概念 在一个程序里,A调用B了,此时如果是 同步: A必须等待B返回结果后,才能继续执行,但是在这期间A会一直监控B的返 ...

  5. spring security基本知识(三) 过滤详细说明

    在我们前面的文章Spring Security 初识(一)中,我们看到了一个最简单的 Spring Security 配置,会要求所有的请求都要经过认证.但是,这并不是我们想要的,我们通常想自定义应用 ...

  6. PHP 大文件上传进度条实现

    核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...

  7. [USACO10HOL]牛的政治Cow Politics

    农夫约翰的奶牛住在N ( <= N <= ,)片不同的草地上,标号为1到N.恰好有N-1条单位长度的双向道路,用各种各样的方法连接这些草地.而且从每片草地出发都可以抵达其他所有草地.也就是 ...

  8. (8)Linux(客户端)和Windows(服务端)下socket通信实例

    Linux(客户端)和Windows(服务端)下socket通信实例: (1)首先是Windows做客户端,Linux做服务端的程序 Windows   Client端 #include <st ...

  9. RabbitMQ消费端自定义监听(九)

    场景: 我们一般在代码中编写while循环,进行consumer.nextDelivery方法进行获取下一条消息,然后进行消费处理. 实际环境: 我们使用自定义的Consumer更加的方便,解耦性更强 ...

  10. slider组件

    slider组件,是一个强大的滑动选择器组件: 属性: min:类型 数字 滑动选择器的(范围)最小值 max:类型 数字 滑动选择器的(范围)最大值 step:类型 数字 步长(滑一次走的距离)  ...