def trapRainWater(heightMap): """ :type heightMap: List[List[int]] :rtype: int """ if not heightMap or not heightMap[0]: return 0 direction = [(1, 0), (-1, 0), (0, 1), (0, -1)] m, n = len(heightMap), len(heightMap[0]) heap = [] visited = set() # Push all the blocks on the border into heap. And create a visit array. for i in range(m): for j in range(n): if i == 0 or i == m - 1 or j == 0 or j == n - 1: heapq.heapqpush(heap, (heightMap[i][j], i, j)) visited.add((i, j)) res = 0 while heap: cur_height, x, y = heapq.heappop(heap) for dir in direction: r, c = x + dir[0], y + dir[1] if r < 0 or r >= m or c < 0 or c >= n or (r, c) in visited: continue res += max(0, cur_height - heightMap[r][c]) heapq.heapqpush(heap, (max(cur_height, heightMap[r][c]), r, c)) visited.add((r, c)) return res
def dijkstra(start): q = [] heapq.heapqpush(q, (0, start)) distance[start] = 0 while q: dist, now = heapq.heaqpop(q) if distance[now] < dist: continue for i in graph[now]: cost = dist + i[1] if cost < distance[i[0]]: distance[i[0]] = cost heapq.heappush(q, (cost, i[0]))
def mergeSortedArr(sortedArrs): sortedArrIters = [iter(x) for x in sortedArrs] minHeap = [] for i, it in enumerate(sortedArrIters): firstElement = next(it, None) if firstElement is not None: heapq.heappush(minHeap, (firstElement, i)) result = [] while minHeap: smallestEntry, smallestArrIndex = heapq.heappop(minHeap) smallestIter = sortedArrIters[smallestArrIndex] result.append(smallestEntry) nextElement = next(smallestIter, None) if nextElement is not None: heapq.heapqpush(minHeap, (nextElement, smallestArrIndex)) return result
def _put(self, item): heapq.heapqpush(self.queue, item)