Faaez Razeen

Min Cost to Connect All Points

  • 2 min read
  • Graph
  • LC-Medium
  • Binary-heap

3 years ago

Solution

TimeSpaceExplanation
O()O()
def minCostConnectPoints(self, points: List[List[int]]) -> int: adj = defaultdict(list) for i in range(len(points)): for j in range(i + 1, len(points)): x1, y1 = points[i] x2, y2 = points[j] dist = abs(x1 - x2) + abs(y1 - y2) adj[i].append((dist, j)) adj[j].append((dist, i)) total_cost = 0 heap = [val for val in adj[0]] heapify(heap) vis = set() vis.add(0) while len(vis) < len(points): next_cost, next_point = heappop(heap) if next_point not in vis: vis.add(next_point) for cost, point in adj[next_point]: if point not in vis: heappush(heap, (cost, point)) total_cost += next_cost return total_cost