Intuition
We want the minimum spanning tree of the complete graph where edge weight is Manhattan distance. Kruskal's algorithm picks the cheapest edges first and adds the ones that don't create a cycle.
Explanation
Approach
- Generate all
O(n²)edges with their Manhattan distances. - Sort edges by weight.
- Walk them in order; use Union-Find to skip edges that would form a cycle. Add weight when an edge merges two components.
- Stop after
n - 1edges.
Complexity
- Time:
O(n² · log n)— sorting dominates. - Space:
O(n²)— the edge list.
Implementation
import java.util.*;
class Solution {
private int[] parent;
private int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public int minCostConnectPoints(int[][] points) {
int n = points.length;
List<int[]> edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int dist = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
edges.add(new int[]{dist, i, j});
}
}
edges.sort((a, b) -> Integer.compare(a[0], b[0]));
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
int cost = 0, used = 0;
for (int[] edge : edges) {
int ra = find(edge[1]), rb = find(edge[2]);
if (ra != rb) {
parent[ra] = rb;
cost += edge[0];
used++;
if (used == n - 1) break;
}
}
return cost;
}
}