Example 1
- Input
- points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
- Output
- 20
Join (2,2) to (5,2) for 3, (0,0) to (2,2) for 4, (5,2) to (7,0) for 4, and (2,2) to (3,10) for 9, totalling 20.
Every pair of points can be joined at their Manhattan distance. Return the cheapest total cost that links all points into one connected network.
You are given points where points[i] = [xi, yi] is a point on the 2D plane. Joining points [xi, yi] and [xj, yj] costs their Manhattan distance |xi - xj| + |yi - yj|.
Return the minimum cost to connect all points, meaning the joined points form exactly one connected network with a single simple path between any two points.
1 <= points.length <= 1000-10^6 <= xi, yi <= 10^6(xi, yi) pairs are distinct.Join (2,2) to (5,2) for 3, (0,0) to (2,2) for 4, (5,2) to (7,0) for 4, and (2,2) to (3,10) for 9, totalling 20.
Join (-4,1) to (-2,5) for 6 and (-2,5) to (3,12) for 12, totalling 18.
One point is already connected. No link is needed, even when its coordinates are at their allowed extremes.
Any three sides of this square form a tree, each costing 1. Taking all four sides would cost 4 and create a cycle; equal-cost choices can produce different trees with the same minimum total.
The network needs n - 1 links without cycles: adding a cycle creates two simple paths between some points and adds unnecessary positive cost. Treat each point as a vertex and each Manhattan distance as an edge weight. Example 1 connects points 0, 1, 3 and 4 for 11, then attaches point 2 for 9. The goal is a minimum spanning tree, which minimizes the sum of chosen links rather than the distance from one source to every point.
Reveal Kruskal Sort All Edges: intuition, complexity, and code
0.On a dense complete graph, growing one tree with a linear closest-distance scan beats sorting every pair.