[Swift]LeetCode407. 接雨水 II | Trapping Rain Water II
阿新 • • 發佈:2019-01-28
png osi ati 計算 false assets note total end
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.
給定一個 m x n
的矩陣,其中的值均為正整數,代表二維高度圖每個單元的高度,請計算圖中形狀最多能接多少體積的雨水。
說明:
m 和 n 都是小於110的整數。每一個單位的高度都大於0 且小於 20000。
示例:
給出如下 3x6 的高度圖: [ [1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1] ] 返回 4。
如上圖所示,這是下雨前的高度圖[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
的狀態。
下雨後,雨水將會被存儲在這些方塊中。總的接雨水量是4。
超出時間限制
1 class Solution { 2 func trapRainWater(_ heightMap: [[Int]]) -> Int { 3 if heightMap.isEmpty {return0} 4 var m:Int = heightMap.count 5 var n:Int = heightMap[0].count 6 var res:Int = 0 7 var mx:Int = Int.min 8 var q:[[Int]] = [[Int]]() 9 var visited:[[Bool]] = [[Bool]](repeating:[Bool](repeating:false,count:n),count:m) 10 var dir:[[Int]] = [[0,-1],[-1,0],[0,1],[1,0]] 11 for i in 0..<m 12 { 13 for j in 0..<n 14 { 15 if i == 0 || i == m - 1 || j == 0 || j == n - 1 16 { 17 q.append([heightMap[i][j], i * n + j]) 18 visited[i][j] = true 19 } 20 } 21 } 22 while(!q.isEmpty) 23 { 24 q = q.sorted { $0[0] == $1[0] ? $0[1] < $1[1] : $0[0] > $1[0] } 25 var t:[Int] = q.removeLast() 26 var h:Int = t[0] 27 var r:Int = t[1] / n 28 var c:Int = t[1] % n 29 mx = max(mx, h) 30 for i in 0..<dir.count 31 { 32 var x:Int = r + dir[i][0] 33 var y:Int = c + dir[i][1] 34 if x < 0 || x >= m || y < 0 || y >= n || visited[x][y] 35 { 36 continue 37 } 38 visited[x][y] = true 39 if heightMap[x][y] < mx 40 { 41 res += mx - heightMap[x][y] 42 } 43 q.append([heightMap[x][y], x * n + y]) 44 } 45 } 46 return res 47 } 48 }
[Swift]LeetCode407. 接雨水 II | Trapping Rain Water II