import heapq M = [[12, 13, 0, 12], [13, 4, 13, 12], [13, 8, 10, 12], [12, 13, 12, 12], [13, 13, 13, 13]] class Solution(object): def trapWater(self, M): heap = [] heapq.heapify(heap) d = [(0, 1), (0, -1), (1, 0), (-1, 0)] n = len(M) m = len(M[0]) visit = [[0 for i in xrange(m)] for I in xrange(n)] res = 0 for i in xrange(n): for I in xrange(m): if i == 0 or I == 0 or i == n-1 or I == m-1: heapq.heappush(heap, (M[i][I], i, I)) visit[i][I] = 1 while heap != []: this = heapq.heappop(heap) for i in xrange(4): h = this[0] nr = this[1] + d[i][0] nl = this[2] + d[i][1] if nr < 0 or nl < 0 or nr >= n or nl >= m: continue if visit[nr][nl] == 1: continue visit[nr][nl] = 1 tmp = M[nr][nl] if tmp < h: res += h - tmp tmp = h heapq.heappush(heap, (tmp, nr, nl)) return res
|