Min Cost to Connect All Points
Medium · Advanced Graphs · Explanation and code example
Prim's Algorithm (Optimal)
How it works
We want to connect all points so that the total cost is minimum, where the cost to connect two points is their Manhattan distance.
This is exactly a Minimum Spanning Tree (MST) problem:
- Think of each point as a node in a graph.
- Every pair of points has an edge with weight = Manhattan distance.
- We need the cheapest way to connect all nodes without forming unnecessary cycles → that’s an MST.
This solution uses Prim’s Algorithm (greedy MST building):
- Start from any node (here, node
0). - Repeatedly add the closest unvisited node to the growing connected set.
- Keep track of the best (minimum) known distance from the current MST to every unvisited node.
Instead of building all edges (which would be too many), we compute distances on the fly and update the best known connection cost for each node.
Steps
- Let
nbe the number of points. - Create:
visit[i]→ whether pointiis already included in the MSTdist[i]→ the minimum cost to connect pointito the current MST (initialize all as infinity)
- Start from
node = 0with total costres = 0and connected edgesedges = 0. - While we have added fewer than
n - 1edges:- Mark the current
nodeas visited (added to MST). - For every unvisited point
i:- Compute cost to connect
ifrom the currentnode - Update
dist[i] = min(dist[i], cost)
- Compute cost to connect
- Choose
nextNodeas the unvisited point with the smallestdist[i]. - Add
dist[nextNode]tores(we are connectingnextNodeto the MST). - Move
node = nextNodeand incrementedges.
- Mark the current
- Return
resas the total minimum cost.
Complexity
- Time complexity:
O(n ^ 2) - Space complexity:
O(n)
Things to watch for
Using Euclidean Distance Instead of Manhattan Distance
The problem specifies Manhattan distance |x1 - x2| + |y1 - y2|, not Euclidean distance. Using the wrong distance formula will produce incorrect edge weights and ultimately a wrong MST cost.
Forgetting to Handle Self-Loops in Edge Generation
When generating all edges between points, ensure you only create edges between distinct points (i.e., i != j). Including self-loops with zero cost can corrupt the Union-Find structure or cause infinite loops in some implementations.
Not Stopping After N-1 Edges in MST Construction
A spanning tree with n nodes has exactly n-1 edges. Continuing to add edges after the MST is complete wastes time and, in some implementations, can cause issues. Always track the number of edges added and stop once you reach n-1.
Python code example
from typing import List
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n, node = len(points), 0
dist = [100000000] * n
visit = [False] * n
edges, res = 0, 0
while edges < n - 1:
visit[node] = True
nextNode = -1
for i in range(n):
if visit[i]:
continue
curDist = (abs(points[i][0] - points[node][0]) +
abs(points[i][1] - points[node][1]))
dist[i] = min(dist[i], curDist)
if nextNode == -1 or dist[i] < dist[nextNode]:
nextNode = i
res += dist[nextNode]
node = nextNode
edges += 1
return res
C++ code example
class Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int n = points.size(), node = 0;
vector<int> dist(n, 100000000);
vector<bool> visit(n, false);
int edges = 0, res = 0;
while (edges < n - 1) {
visit[node] = true;
int nextNode = -1;
for (int i = 0; i < n; i++) {
if (visit[i]) continue;
int curDist = abs(points[i][0] - points[node][0]) +
abs(points[i][1] - points[node][1]);
dist[i] = min(dist[i], curDist);
if (nextNode == -1 || dist[i] < dist[nextNode]) {
nextNode = i;
}
}
res += dist[nextNode];
node = nextNode;
edges++;
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.