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. 长沙理工大学第十二届ACM大赛-重现赛I 主持人的烦恼 (sort)

    链接:https://ac.nowcoder.com/acm/contest/1/I 来源:牛客网 主持人的烦恼 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 131072K,其他语 ...

  2. GUI学习之三十三——QProgressBar学习总结

    今天总结的是QProgressBar的使用方法 一.描述 提供了一个水平或垂直的进度条,用于向用户提供操作进度的指示,用户也可以从进度条看出来程序是否正在运行. 二.功能作用 1.设置范围和当前值 Q ...

  3. <转>ThinkPHP的开发常用系统配置项

    /* 项目设定 */ ’APP_DEBUG’ => false, // 是否开启调试模式 ’APP_DOMAIN_DEPLOY’ => false, // 是否使用独立域名部署项目 ’AP ...

  4. 在目标端重建sequence的脚本

    select 'create sequence '||SEQUENCE_OWNER||'.'||sequence_name|| ' minvalue '||min_value|| ' maxvalue ...

  5. pyautogui页面点击和键盘输入

    以下程序实现了在编辑框处点击,然后用键盘输入的功能 import pyautogui import time time.sleep(10) currentMouseX, currentMouseY = ...

  6. 查看jar包内容

    查看jar包内容 查看jar包内容的基本命令: jar tf jar-file 参数解释: The t option indicates that you want to view the table ...

  7. Java各种锁机制简述

    线程安全是多线程领域的问题,线程安全可以简单理解为一个方法或者一个实例可以在多线程环境中使用而不会出现问题. 在 Java 多线程编程当中,提供了多种实现 Java 线程安全的方式: 最简单的方式,使 ...

  8. Codeforces Round #350(Div 2)

    因为当天的下午才看到所以没来得及请假所以这一场没有打...于是信息课就打了这场的模拟赛. A题: *题目描述: 火星上的一年有n天,问每年最少和最多有多少休息日(周六周天). *题解: 模7分类讨论一 ...

  9. VMware 15 搭建MacOS 10.14教程

    写于2018.12.23 教程原文链接:https://pan.baidu.com/s/1wvNYg_MQH_lwewKbpCQ5_Q ———————————————————————————————— ...

  10. 在centos上配置环境

    1.   安装wget [root@localhost ~]# yum -y install wget 2.   在oneinstack官网配置安装环境 wget http://mirrors.lin ...