Given points on a 2D plane, the cost of connecting two points is their Manhattan distance. Return the minimum total cost to connect all points (so there is exactly one path between any two).
List all n² edges, sort by length, and add each edge whose endpoints are in different components (union-find), until n − 1 edges are in.
1function minCostConnectPoints(points: number[][]): number {2const n = points.length, edges: [number, number, number][] = [];3for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++)4edges.push([Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]), i, j]);5edges.sort((a, b) => a[0] - b[0]);6const parent = Array.from({ length: n }, (_, i) => i);7const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));8let total = 0, used = 0;9for (const [d, i, j] of edges) {10if (used === n - 1) break;11const a = find(i), b = find(j);12if (a === b) continue;13parent[a] = b; total += d; used++;14}15return total;16}
Sort all 10 edges by length.
Space: play/pause · ←/→: step