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
assert Solution().minCostConnectPoints([[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]) == 20
assert Solution().minCostConnectPoints([[3, 12], [-2, 5], [-4, 1]]) == 18
class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length, total = 0;
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[0] = 0;
boolean[] used = new boolean[n];
for (int it = 0; it < n; it++) {
int u = -1;
for (int i = 0; i < n; i++) if (!used[i] && (u == -1 || dist[i] < dist[u])) u = i;
used[u] = true;
total += dist[u];
for (int v = 0; v < n; v++)
if (!used[v])
dist[v] = Math.min(dist[v], Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]));
}
return total;
}
}
func minCostConnectPoints(points [][]int) int {
n := len(points)
dist := make([]int, n) // cheapest edge from the tree to each point
for i := range dist {
dist[i] = math.MaxInt
}
dist[0] = 0
used := make([]bool, n)
total := 0
for step := 0; step < n; step++ { // dense Prim: O(n^2)
u := -1
for i := 0; i < n; i++ {
if !used[i] && (u == -1 || dist[i] < dist[u]) {
u = i
}
}
used[u] = true
total += dist[u]
for v := 0; v < n; v++ {
if !used[v] {
dist[v] = min(dist[v], abs(points[v][0]-points[u][0])+abs(points[v][1]-points[u][1]))
}
}
}
return total
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}