Min cost to connect points
Standard · Write code · about 15 min
Each point [x, y] must be joined to every other point, directly or through other points. Joining two points costs their Manhattan distance |x1 − x2| + |y1 − y2|. Return the minimum total cost.
Example 1
Input:
[[[0,0],[2,2],[3,10],[5,2],[7,0]]]
Output:
20
One cheapest set of links: 0-1 (4), 1-3 (3), 3-4 (4), 1-2 (9).
Example 2
Input:
[[[3,12],[-2,5],[-4,1]]]
Output:
18
Link 1-2 (6) and 0-1 (12).
Constraints
- 1 ≤ points.length ≤ 500
- -1,000,000 ≤ x, y ≤ 1,000,000
- All points are different.
Learn the idea first: Kruskal's algorithm, a visual lesson.
More Kruskal's algorithm problems
- MST edges in order Warm-up
- Accept or reject? Warm-up
- Implement Kruskal Standard
- Spot the bug: linking the wrong vertex Standard
- Critical and pseudo-critical edges Challenge