Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3cc4f69

Browse files
committed
Add solution #407
1 parent afbbbc9 commit 3cc4f69

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

0407-trapping-rain-water-ii.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 407. Trapping Rain Water II
3+
* https://leetcode.com/problems/trapping-rain-water-ii/
4+
* Difficulty: Hard
5+
*
6+
* Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D
7+
* elevation map, return the volume of water it can trap after raining.
8+
*/
9+
10+
/**
11+
* @param {number[][]} heightMap
12+
* @return {number}
13+
*/
14+
var trapRainWater = function(heightMap) {
15+
const minHeap = new MinPriorityQueue({ priority: ([value]) => value });
16+
const history = new Array(heightMap.length).fill(0)
17+
.map(() => new Array(heightMap[0].length).fill(false));
18+
19+
for (let i = 0; i < heightMap.length; i++) {
20+
for (let j = 0; j < heightMap[0].length; j++) {
21+
if (i === 0 || i === heightMap.length - 1 || j === 0 || j === heightMap[0].length - 1) {
22+
minHeap.enqueue([heightMap[i][j], i, j]);
23+
history[i][j] = true;
24+
}
25+
}
26+
}
27+
28+
let result = 0;
29+
while (minHeap.size()) {
30+
const [weight, i, j] = minHeap.dequeue().element;
31+
[[0, 1], [1, 0], [0, -1], [-1, 0]].forEach(([x, y]) => {
32+
const [rowIndex, columnIndex] = [i + x, j + y];
33+
if (rowIndex >= 0 && rowIndex < heightMap.length && columnIndex >= 0
34+
&& columnIndex < heightMap[0].length && !history[rowIndex][columnIndex]) {
35+
result += Math.max(0, weight - heightMap[rowIndex][columnIndex]);
36+
minHeap.enqueue([
37+
Math.max(weight, heightMap[rowIndex][columnIndex]), rowIndex, columnIndex
38+
]);
39+
history[rowIndex][columnIndex] = true;
40+
}
41+
});
42+
}
43+
44+
return result;
45+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@
197197
394|[Decode String](./0394-decode-string.js)|Medium|
198198
395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium|
199199
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|
200+
407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard|
200201
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|
201202
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|
202203
415|[Add Strings](./0415-add-strings.js)|Easy|

0 commit comments

Comments
 (0)