Algo-Sim › Advanced Graphs
Min Cost to Connect All Points
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
Join every point at the least total Manhattan distance: a minimum spanning tree of the complete graph. Prim's algorithm with a plain dist array, O(n²) and no heap.
Problem
You are given distinct points on a grid, points[i] = [xᵢ, yᵢ]. Joining two points costs their Manhattan distance |xᵢ − xⱼ| + |yᵢ − yⱼ|. Return the minimum total cost to connect all the points, so that every pair is joined by exactly one simple path.
Constraints
- 1 ≤ points.length ≤ 1000
- −10⁶ ≤ xᵢ, yᵢ ≤ 10⁶
- All points are distinct
Edge cases to test
- One point:
0 - Duplicate points
- Points on a line
Follow-up questions
- Why array-based Prim here?
- The graph is complete (n² edges), so O(n²) Prim beats sorting all edges for Kruskal (O(n² log n)).
- Can it be faster than O(n²)?
- For Manhattan distance, only O(n) candidate edges per octant matter, which gives O(n log n) with sweeps.
Solution
Java
public int minCostConnectPoints(int[][] points) {
int n = points.length;
int[] dist = new int[n];
boolean[] inTree = new boolean[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[0] = 0;
int total = 0;
for (int round = 0; round < n; round++) {
int u = -1;
for (int v = 0; v < n; v++) {
if (!inTree[v] && (u == -1 || dist[v] < dist[u])) u = v;
}
inTree[u] = true;
total += dist[u];
for (int v = 0; v < n; v++) {
if (inTree[v]) continue;
int 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;
}Python
def min_cost_connect_points(points):
n = len(points)
dist = [float("inf")] * n
in_tree = [False] * n
dist[0] = 0
total = 0
for _ in range(n):
u = -1
for v in range(n):
if not in_tree[v] and (u == -1 or dist[v] < dist[u]):
u = v
in_tree[u] = True
total += dist[u]
for v in range(n):
if in_tree[v]:
continue
d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1])
if d < dist[v]:
dist[v] = d
return totalC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minCostConnectPoints(vector<vector<int>> &points) {
int n = int(points.size());
vector<int> dist(n, INT_MAX);
vector<bool> inTree(n, false);
dist[0] = 0;
int total = 0;
for (int round = 0; round < n; round++) {
int u = -1;
for (int v = 0; v < n; v++) {
if (!inTree[v] && (u == -1 || dist[v] < dist[u])) {
u = v;
}
}
inTree[u] = true;
total += dist[u];
for (int v = 0; v < n; v++) {
if (inTree[v]) {
continue;
}
int d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]);
if (d < dist[v]) {
dist[v] = d;
}
}
}
return total;
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)