SDE & MLE Prep

1584. Min Cost to Connect All Points

Problem

Connect all points on a plane; joining two points costs their Manhattan distance |x₁ − x₂| + |y₁ − y₂|. Return the minimum total cost so that every pair of points is connected (directly or through others).

Example: [[0,0],[2,2],[3,10],[5,2],[7,0]] → 20

Constraints: up to 1000 points.

Complete graph with Manhattan weights → Prim's O(n²) array version (no heap needed for dense graphs): repeatedly add the closest outside point, then update distances.

Complexity: O(n²).

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        INF = float("inf")
        dist = [INF] * n
        dist[0] = 0
        used = [False] * n
        total = 0
        for _ in range(n):
            u = min((d, i) for i, d in enumerate(dist) if not used[i])[1]
            used[u] = True
            total += dist[u]
            ux, uy = points[u]
            for v in range(n):
                if not used[v]:
                    dist[v] = min(dist[v], abs(points[v][0] - ux) + abs(points[v][1] - uy))
        return total