|
| 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 | +}; |
0 commit comments