Swift💯Heap; Fast: 2ms
Heap (accepted answer)
**Heap (accepted answer)**
```
class Solution {
    struct HeapItem:Comparable {
        let x,y,z:Int
        static func <(l:Self,r:Self)->Bool {l.z < r.z}
    }
    func trapRainWater(_ heights: [[Int]]) -> Int {
        let (rows, cols) = (heights.count, heights[0].count)
        let borders = chain(
            (0..<rows).lazy.flatMap {y in [(0,y),(cols-1,y)]},
            (0..<cols).lazy.flatMap {x in [(x,0),(x,rows-1)]}
        )
        var heap = Heap(borders.map{x,y in HeapItem(x:x, y:y, z:heights[y][x]) })
        var visited = Array(repeating: false, count: cols*rows)
        borders.forEach {x,y in visited[y*cols + x] = true}
        var count = 0

        while let item = heap.popMin() {
            for (dx,dy) in [0,1,0,-1,0].adjacentPairs() {
                let (x,y) = (item.x + dx, item.y + dy)
                guard
                    0..<rows ~= y, 0..<cols ~= x,
                    !visited[y*cols + x]
                else { continue }
                heap.insert(HeapItem(x:x, y:y, z:max(heights[y][x], item.z)))
                visited[y*cols + x] = true
                count += max(0, item.z - heights[y][x])
            }
        }
        return count
    }
}
```
['Swift', 'Heap (Priority Queue)']