[LeetCode] 407. Trapping Rain Water II 收集雨水 II

时间:2022-01-22 13:39:24

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.

[LeetCode] 407. Trapping Rain Water II 收集雨水 II
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.

[LeetCode] 407. Trapping Rain Water II 收集雨水 II
After the rain, water is trapped between the blocks. The total volume of water trapped is 4.

42. Trapping Rain Water的拓展,由2D变3D了。解法跟之前的完全不同了,之前那道题由于是二维的,我们可以用双指针来做,而这道三维的,我们需要用BFS来做。

Java: Priority Queue

public class Solution {

    public 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;
}
} public int trapRainWater(int[][] heights) {
if (heights == null || heights.length == 0 || heights[0].length == 0)
return 0; PriorityQueue<Cell> queue = new PriorityQueue<>(1, new Comparator<Cell>(){
public int compare(Cell a, Cell b) {
return a.height - b.height;
}
}); int m = heights.length;
int n = heights[0].length;
boolean[][] visited = new boolean[m][n]; // Initially, add all the Cells which are on borders to the queue.
for (int i = 0; i < m; i++) {
visited[i][0] = true;
visited[i][n - 1] = true;
queue.offer(new Cell(i, 0, heights[i][0]));
queue.offer(new Cell(i, n - 1, heights[i][n - 1]));
} for (int i = 0; i < n; i++) {
visited[0][i] = true;
visited[m - 1][i] = true;
queue.offer(new Cell(0, i, heights[0][i]));
queue.offer(new Cell(m - 1, i, heights[m - 1][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[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int res = 0;
while (!queue.isEmpty()) {
Cell cell = queue.poll();
for (int[] dir : dirs) {
int row = cell.row + dir[0];
int col = cell.col + dir[1];
if (row >= 0 && row < m && col >= 0 && col < n && !visited[row][col]) {
visited[row][col] = true;
res += Math.max(0, cell.height - heights[row][col]);
queue.offer(new Cell(row, col, Math.max(heights[row][col], cell.height)));
}
}
} return res;
}
}  

Python:

from heapq import heappush, heappop

class Solution(object):
def trapRainWater(self, heightMap):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
m = len(heightMap)
if not m:
return 0
n = len(heightMap[0])
if not n:
return 0 is_visited = [[False for i in xrange(n)] for j in xrange(m)] heap = []
for i in xrange(m):
heappush(heap, [heightMap[i][0], i, 0])
is_visited[i][0] = True
heappush(heap, [heightMap[i][n-1], i, n-1])
is_visited[i][n-1] = True
for j in xrange(n):
heappush(heap, [heightMap[0][j], 0, j])
is_visited[0][j] = True
heappush(heap, [heightMap[m-1][j], m-1, j])
is_visited[m-1][j] = True trap = 0
while heap:
height, i, j = heappop(heap)
for (dx, dy) in [(1,0), (-1,0), (0,1), (0,-1)]:
x, y = i+dx, j+dy
if 0 <= x < m and 0 <= y < n and not is_visited[x][y]:
trap += max(0, height - heightMap[x][y])
heappush(heap, [max(height, heightMap[x][y]), x, y])
is_visited[x][y] = True return trap  

C++:

class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.empty()) return 0;
int m = heightMap.size(), n = heightMap[0].size(), res = 0, mx = INT_MIN;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
vector<vector<bool>> visited(m, vector<bool>(n, false));
vector<vector<int>> dir{{0,-1},{-1,0},{0,1},{1,0}};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
q.push({heightMap[i][j], i * n + j});
visited[i][j] = true;
}
}
}
while (!q.empty()) {
auto t = q.top(); q.pop();
int h = t.first, r = t.second / n, c = t.second % n;
mx = max(mx, h);
for (int i = 0; i < dir.size(); ++i) {
int x = r + dir[i][0], y = c + dir[i][1];
if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue;
visited[x][y] = true;
if (heightMap[x][y] < mx) res += mx - heightMap[x][y];
q.push({heightMap[x][y], x * n + y});
}
}
return res;
}
};

 

类似题目:

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

All LeetCode Questions List 题目汇总

 

[LeetCode] 407. Trapping Rain Water II 收集雨水 II的更多相关文章

  1. &lbrack;LeetCode&rsqb; 407&period; Trapping Rain Water II 收集雨水之二

    Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...

  2. leetCode 42&period;Trapping Rain Water&lpar;凹槽的雨水&rpar; 解题思路和方法

    Trapping Rain Water Given n non-negative integers representing an elevation map where the width of e ...

  3. &lbrack;leetcode&rsqb; 407&period; Trapping Rain Water II

    https://leetcode.com/contest/6/problems/trapping-rain-water-ii/ 看到这题,我很高兴,因为我做过!哈哈!其实我现在也写不出来,知道大概思想 ...

  4. leetcode 11&period; Container With Most Water 、42&period; Trapping Rain Water 、238&period; Product of Array Except Self 、407&period; Trapping Rain Water II

    11. Container With Most Water https://www.cnblogs.com/grandyang/p/4455109.html 用双指针向中间滑动,较小的高度就作为当前情 ...

  5. leetcode&num;42 Trapping rain water的五种解法详解

    leetcode#42 Trapping rain water 这道题十分有意思,可以用很多方法做出来,每种方法的思想都值得让人细细体会. 42. Trapping Rain WaterGiven n ...

  6. &lbrack;array&rsqb; leetcode - 42&period; Trapping Rain Water - Hard

    leetcode - 42. Trapping Rain Water - Hard descrition Given n non-negative integers representing an e ...

  7. LeetCode 42&period; Trapping Rain Water 【两种解法】(python排序遍历,C&plus;&plus; STL map存索引,时间复杂度O(nlogn))

    LeetCode 42. Trapping Rain Water Python解法 解题思路: 本思路需找到最高点左右遍历,时间复杂度O(nlogn),以下为向左遍历的过程. 将每一个点的高度和索引存 ...

  8. &lbrack;LeetCode&rsqb; 42&period; Trapping Rain Water 收集雨水

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

  9. LeetCode - 42&period; Trapping Rain Water

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

随机推荐

  1. 解决eclipse ctrl&plus;鼠标左键不能用

    选择[Window]菜单 Preferences ——>General——>Editors——>Text Editors——>Hyperlinking 把勾都点上,然后确定KE ...

  2. 二、JavaScript语言--JS基础--JavaScript进阶篇--JS基础语法

    1.变量 定义:从字面上看,变量是可变的量:从编程角度讲,变量是用于存储某种/某些数值的存储器.我们可以把变量看做一个盒子,盒子用来存放物品,物品可以是衣服.玩具.水果...等. 命名:变量名字可以任 ...

  3. &lbrack;改善Java代码&rsqb;使用forName动态加载类文件

    动态加载(Dynamic Loading)是指在程序运行时加载需要的类库文件,对Java程序来说,一般情况下,一个类文件在启动时或首次初始化时会被加载到内存中,而反射则可以在运行时再决定是否需要加载一 ...

  4. 【Python】使用多个迭代器

    如果要达到多个迭代器的效果,__iter__()只需替迭代器定义新的状态对象,而不是返回self class SkipIterator: def __init__(self, wrapped): se ...

  5. &lbrack;译&rsqb;Selenium Python文档:一、安装

    1.1.简介 Selenium Python为使用Selenium WebDriver来编写功能/验证测试提供了一个简单的API接口.通过Selenium Python API,你可以以一种非常直观的 ...

  6. 常见形式 Web API 的简单分类总结

    一.请求--响应API. 请求--响应类的API的典型做法是,通过基于HTTP的Web服务器暴露一个/套接口.API定义一些端点,客户端发送数据的请求到这些端点,Web服务器处理这些请求,然后返回响应 ...

  7. Debian 9&period;x &quot&semi;stretch&quot&semi; 安装 vnStat 统计服务器流量

    vnStat 是一款开源的 Linux 下统计网卡流量的软件,可以很方便地查看当前.当天.当月的流量统计报告,下面我们介绍下在 Debian 9.x 下安装 vnstat 的简单方法 首先,使用 ip ...

  8. Yii2 nginx配置伪静态

    Yii2 配置 Nginx 伪静态 主要检查以下代码: location / { # Redirect everything that isn't a real file to index.php t ...

  9. 解决Installation error&colon; INSTALL&lowbar;FAILED&lowbar;VERSION&lowbar;DOWNGRADE错误

    Installation error: INSTALL_FAILED_VERSION_DOWNGRADE 说明你手机里已经装的软件版本比你要安装的软件版本要高,所以不能安装. 你只要删除你安装的应用便 ...

  10. 关于 android 读取当前手机号码

    手机号码不是所有的都能获取.只是有一部分可以拿到.这个是由于移动运营商没有把手机号码的数据写入到sim卡中.SIM卡只有唯一的编号,供网络与设备识别那就是IMSI号码,手机的信号也可以说是通过这个号码 ...