Min Cost to Connect All Points
Medium
Topics
You are given points where points[i] = [x, y]. The cost to connect two points is their Manhattan distance. Return the minimum cost to connect all points so every pair is reachable. (Input rows are the points.)
Example 1
Node
i is point [0, 0]-style coordinate points[i], and every pair is joinable at its Manhattan distance. The answer is the cheapest set of 4 edges that still connects everything — a minimum spanning tree, total 20. Edge labels are those distances.Input is a list of
[x, y] points; the figure shows the chosen spanning tree with its edge weights.Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] Output: 20
Example 2
Input: points = [[3,12],[-2,5],[-4,1]] Output: 18
Constraints
- 1 <= points.length <= 1000
- -10^6 <= xi, yi <= 10^6
Editorial — intuition, approach, complexity and pitfalls
Intuition
This is a minimum spanning tree on a complete graph where edge weights are Manhattan distances. Prim’s algorithm grows the tree by repeatedly adding the cheapest edge to a new point.
Approach
- Start from any point; track the min distance from the growing tree to each outside point.
- Repeatedly pick the closest outside point, add its distance to the total, and mark it in the tree.
- Update the distances of remaining points against the newly added one.
Dry Run
points [0,0] [2,2] [3,10] [5,2] [7,0], Manhattan distance
Prim's: dist[v] is the cheapest known edge from the tree so far to v, not a path
length. Grow the tree one node at a time, always taking the cheapest fringe.
pick 0 cost 0 total 0 dist becomes [0, 4, 13, 7, 7]
pick 1 cost 4 total 4 improves dist[2] 13->9, dist[3] 7->3
pick 3 cost 3 total 7 improves dist[4] 7->4
pick 4 cost 4 total 11 improves nothing
pick 2 cost 9 total 20 improves nothing
answer 20
Watch dist[3] fall from 7 to 3 when node 1 joins. Each new tree node can only
make the fringe cheaper, never more expensive, which is why relaxing with
`if d < dist[v]` is required -- assign unconditionally and a cheaper edge found
earlier is overwritten by whatever the newest node happens to cost, giving 25
instead of 20.
The `not in_mst[i]` filter in the SELECTION loop is what makes this Prim's rather
than an infinite shuffle. Without it the cheapest node is always one already in
the tree, at dist 0, so the total comes out 0 for every input.
The same-looking filter in the RELAXATION loop is not load-bearing, which is worth
knowing before hunting a bug: a node already in the tree can have its dist
lowered harmlessly, because it will never be selected again. Removing that one
changes no answer across 3000 random point sets.
No edge list is built. All n^2 distances are computed on demand, which is the
right call on a complete geometric graph -- materialising 10^6 edges to sort them
would cost more than this O(n^2) scan.Complexity
- Time — O(n^2): dense Prim’s over all point pairs.
- Space — O(n): the distance and in-tree arrays.
Common Pitfalls
- Relax with
if d < dist[v]. Assigningdist[v] = dunconditionally overwrites a cheaper edge found earlier with whatever the newest tree node happens to cost, and the total comes out 25 instead of 20. - The
not in_mst[i]filter is what makes this Prim's rather than a loop. Without it the nearest node is always one already in the tree at distance 0, so the total is 0 for every input. - The identical-looking filter in the relaxation loop is not load-bearing, which is worth knowing before you hunt for a bug there. A node already in the tree can have its
distlowered harmlessly, since it will never be selected again; removing that filter changes no answer across 3000 random point sets.
Full Solution — all languages
class Solution:
def minCostConnectPoints(self, grid):
pts=grid; n=len(pts)
if n<=1: return 0
in_mst=[False]*n; dist=[float('inf')]*n; dist[0]=0; total=0
for _ in range(n):
u=-1
for i in range(n):
if not in_mst[i] and (u==-1 or dist[i]<dist[u]): u=i
in_mst[u]=True; total+=dist[u]
for v in range(n):
if not in_mst[v]:
d=abs(pts[u][0]-pts[v][0])+abs(pts[u][1]-pts[v][1])
if d<dist[v]: dist[v]=d
return totalimport java.util.*;
class Solution {
public int minCostConnectPoints(int[][] grid) {
int[][] pts=grid;
int n=pts.length;
if(n<=1)return 0;
boolean[] inMst=new boolean[n];
long[] dist=new long[n];
Arrays.fill(dist,Long.MAX_VALUE);
dist[0]=0;
long total=0;
for(int it=0;it<n;it++) {
int u=-1;
for(int i=0;i<n;i++)if(!inMst[i]&&(u==-1||dist[i]<dist[u]))u=i;
inMst[u]=true;
total+=dist[u];
for(int v=0;v<n;v++)if(!inMst[v]) {
long d=Math.abs(pts[u][0]-pts[v][0])+Math.abs(pts[u][1]-pts[v][1]);
if(d<dist[v])dist[v]=d;
}
}
return (int)total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minCostConnectPoints(vector<vector<int>>& grid) {
auto& pts=grid;
int n=pts.size();
if(n<=1)return 0;
vector<char> inMst(n,0);
vector<long long> dist(n,LLONG_MAX);
dist[0]=0;
long long total=0;
for(int it=0;it<n;it++) {
int u=-1;
for(int i=0;i<n;i++)if(!inMst[i]&&(u==-1||dist[i]<dist[u]))u=i;
inMst[u]=1;
total+=dist[u];
for(int v=0;v<n;v++)if(!inMst[v]) {
long long d=abs(pts[u][0]-pts[v][0])+abs(pts[u][1]-pts[v][1]);
if(d<dist[v])dist[v]=d;
}
}
return (int)total;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var minCostConnectPoints = function(grid) {
const pts=grid,n=pts.length;
if(n<=1)return 0;
const inMst=new Array(n).fill(false),dist=new Array(n).fill(Infinity);
dist[0]=0;
let total=0;
for(let it=0;it<n;it++) {
let u=-1;
for(let i=0;i<n;i++)if(!inMst[i]&&(u===-1||dist[i]<dist[u]))u=i;
inMst[u]=true;
total+=dist[u];
for(let v=0;v<n;v++)if(!inMst[v]) {
const d=Math.abs(pts[u][0]-pts[v][0])+Math.abs(pts[u][1]-pts[v][1]);
if(d<dist[v])dist[v]=d;
}
}
return total;
};