python heap solution, 15 lines
python\nclass Solution:\n    def trapRainWater(self, hm):\n        if not hm or not hm[0]: return 0\n        m, n, res = len(hm), len(hm[0]), 0\n        heap = 
```python\nclass Solution:\n    def trapRainWater(self, hm):\n        if not hm or not hm[0]: return 0\n        m, n, res = len(hm), len(hm[0]), 0\n        heap = list(set([(hm[i][0], i, 0) for i in range(m)] + [(hm[i][n - 1], i, n - 1) for i in range(m)] + [(hm[0][j], 0, j) for j in range(n)] + [(hm[m - 1][j], m - 1, j) for j in range(n)]))\n        heapq.heapify(heap)\n        seen = {(x, y) for h, x, y in heap}\n        while heap:\n            h, x, y = heapq.heappop(heap)\n            for d in ((1, 0), (-1, 0), (0, 1), (0, -1)):\n                xx, yy = x + d[0], y + d[1]\n                if not (xx >= m or xx < 0 or yy >= n or yy < 0 or (xx, yy) in seen): \n                    seen.add((xx, yy))\n                    res += max(0, h - hm[xx][yy])\n                    heapq.heappush(heap, (max(h, hm[xx][yy]), xx, yy))\n        return res\n```
[]