MediumGraphs · Minimum Spanning Tree · Union-Find

Min Cost to Connect Points

Connecting [x1, y1] and [x2, y2] costs the Manhattan distance |x1 − x2| + |y1 − y2|. Return the minimum total cost so that every pair of points is joined by exactly one path.

points = [[0,0],[2,2],[3,3],[2,4],[4,2]] → 10

Try:
CALL
1 / 1

Code

The highlighted line runs next. The pill shows the live values in the running call.

Variables

The data structures the code is building

The points

Lines show edge costs; the dotted elbow is the Manhattan route

Time and space complexity

n = number of points. The highlighted row is the solution being traced.

Keyboard: ← → step, Space play or pause. Up to 7 distinct points with coordinates from −99 to 99.