|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# https://leetcode.com/problems/trapping-rain-water-ii/ |
| 4 | +# @param {Integer[][]} height_map |
| 5 | +# @return {Integer} |
| 6 | +def trap_rain_water(height_map) |
| 7 | + trapped_water = 0 |
| 8 | + water_level_map = ::Array.new(height_map.size) { ::Array.new(height_map[0].size, 20_000) } |
| 9 | + |
| 10 | + (1...height_map.size - 1).each do |i| |
| 11 | + water_level_map[i][0] = height_map[i][0] |
| 12 | + |
| 13 | + (1...height_map[i].size - 1).each { |j| water_level_map[i][j] = 20_000 } |
| 14 | + |
| 15 | + water_level_map[i][height_map[i].size - 1] = height_map[i][height_map[i].size - 1] |
| 16 | + end |
| 17 | + |
| 18 | + (0...height_map[0].size).each do |i| |
| 19 | + water_level_map[0][i] = height_map[0][i] |
| 20 | + water_level_map[height_map.size - 1][i] = height_map[height_map.size - 1][i] |
| 21 | + end |
| 22 | + |
| 23 | + drain = true |
| 24 | + while drain |
| 25 | + drain = false |
| 26 | + (1...height_map[0].size - 1).each do |i| |
| 27 | + (1...height_map.size - 1).each do |j| |
| 28 | + next unless water_level_map[j][i] > height_map[j][i] |
| 29 | + |
| 30 | + water_level_map[j][i] = [water_level_map[j][i - 1], height_map[j][i]].max if water_level_map[j][i] > water_level_map[j][i - 1] |
| 31 | + water_level_map[j][i] = [water_level_map[j - 1][i], height_map[j][i]].max if water_level_map[j][i] > water_level_map[j - 1][i] |
| 32 | + end |
| 33 | + end |
| 34 | + |
| 35 | + (height_map[0].size - 2).downto(1) do |i| |
| 36 | + (height_map.size - 2).downto(1) do |j| |
| 37 | + next unless water_level_map[j][i] > height_map[j][i] |
| 38 | + |
| 39 | + water_level_map[j][i] = [water_level_map[j][i + 1], height_map[j][i]].max if water_level_map[j][i] > water_level_map[j][i + 1] |
| 40 | + water_level_map[j][i] = [water_level_map[j + 1][i], height_map[j][i]].max if water_level_map[j][i] > water_level_map[j + 1][i] |
| 41 | + |
| 42 | + next unless water_level_map[j][i] < water_level_map[j][i + 1] && water_level_map[j][i + 1] > height_map[j][i + 1] || |
| 43 | + water_level_map[j][i] < water_level_map[j + 1][i] && water_level_map[j + 1][i] > height_map[j + 1][i] |
| 44 | + |
| 45 | + drain = true |
| 46 | + end |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + (1...water_level_map.size - 1).each do |i| |
| 51 | + (1...water_level_map[i].size - 1).each do |j| |
| 52 | + trapped_water += water_level_map[i][j] - height_map[i][j] |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + trapped_water |
| 57 | +end |
0 commit comments