Min Cost to Connect All Points
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #1584
Given points on a 2-D plane, the cost of connecting two points is their Manhattan distance |x1−x2| + |y1−y2|. Return the minimum total cost to connect all points, so that every pair has exactly one simple path between them.
Examples
text
[[0,0],[2,2],[3,10],[5,2],[7,0]] → 20
[[3,12],[-2,5],[-4,1]] → 18Hints
- "Connect everything as cheaply as possible, exactly one path between each pair" is a minimum spanning tree.
- The graph is complete (n² edges). Kruskal must sort all of them. Prim with an array instead of a heap runs in O(n²) with no edge list at all.
Approach
Dense Prim:
text
dist[i] = cost to connect i to the growing tree (initially inf; dist[0] = 0)
repeat n times:
u = unvisited point with the smallest dist # O(n) scan
total += dist[u]; visited[u] = True
for every unvisited v: dist[v] = min(dist[v], manhattan(u, v))That's O(n²) time and O(n) space. For a complete graph this beats Kruskal's O(n² log n) and heap-Prim's O(n² log n), because every pair is an edge anyway. The cut property is why the greedy is correct: the cheapest edge crossing any cut belongs to some MST.
Complexity
Time: O(n²). Space: O(n).
Python solution
def minCostConnectPoints(points):
n = len(points)
dist = [float('inf')] * n
dist[0] = 0
seen = [False] * n
total = 0
for _ in range(n):
u = min((i for i in range(n) if not seen[i]), key=lambda i: dist[i])
seen[u] = True
total += dist[u]
ux, uy = points[u]
for v in range(n):
if not seen[v]:
d = abs(ux - points[v][0]) + abs(uy - points[v][1])
if d < dist[v]:
dist[v] = d
return totalJavaScript solution
function minCostConnectPoints(points) {
const n = points.length, dist = new Array(n).fill(Infinity), seen = new Array(n).fill(false);
dist[0] = 0;
let total = 0;
for (let it = 0; it < n; it++) {
let u = -1;
for (let i = 0; i < n; i++) if (!seen[i] && (u === -1 || dist[i] < dist[u])) u = i;
seen[u] = true; total += dist[u];
for (let v = 0; v < n; v++) if (!seen[v]) {
const d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
if (d < dist[v]) dist[v] = d;
}
}
return total;
}