Min Cost to Connect All Points

MediumMinimum spanning treeLeetCode 1584 ↗World 6-20
0:00 / 0:00

Join every point with the least total Manhattan distance. Grow a minimum spanning tree with Prim's algorithm, cheapest link first.

▼

The problem

LeetCode 1584 (Medium). Given points[i] = [xi, yi] on a 2D plane, the cost of connecting two points is their Manhattan distance |xi - xj| + |yi - yj|. Return the minimum cost to connect all the points, where all points are connected if there is exactly one simple path between any two of them.

Examples (LeetCode's): [[0,0],[2,2],[3,10],[5,2],[7,0]] → 20 and [[3,12],[-2,5],[-4,1]] → 18.

TRY IT ON LEETCODE ▶

The solution

def minCostConnectPoints(points):
    n = len(points)
    dist = [float('inf')] * n   # cheapest link
    dist[0] = 0
    seen = [False] * n
    total = 0
    for _ in range(n):
        u = min((d, i) for i, d in enumerate(dist) if not seen[i])[1]
        seen[u] = True
        total += dist[u]
        x, y = points[u]
        for v, (a, b) in enumerate(points):
            if not seen[v]:
                dist[v] = min(dist[v], abs(x - a) + abs(y - b))
    return total

Transcript

Min Cost to Connect All Points. Picture pins on a corkboard grid. Yarn between two pins runs along the grid lines, so a link costs the gap in x plus the gap in y. Connect every pin using the least yarn.

Here are five pins: zero zero, two two, three ten, five two and seven zero. The cheapest network that ties them all costs twenty.

The best network has no loops, so it's a spanning tree. Trying them all is hopeless: five pins have a hundred twenty-five, and ten pins have a hundred million. Tying each pin to its nearest neighbor is quick, but it can leave separate islands.

Prim's algorithm grows one tree instead. Start at pin zero. Every pin outside remembers its cheapest link into the tree. Each round, add the pin whose link is cheapest. Then the others check the newcomer: if it's closer, their link gets cheaper. The cheapest link out of the tree is always safe.

From zero zero, the others note four, thirteen, seven and seven. Two two is cheapest, so add four. Now three ten drops to nine, and five two to three. Take five two for three. Seven zero is now four away: take it. Last, three ten joins through two two for nine. Four, three, four and nine make twenty.

In code, a distance array holds each pin's cheapest link, all infinity except pin zero. A seen array marks the tree. Loop n times: take the unseen pin with the smallest distance, mark it, and add its distance to the total. Then every unseen pin keeps the smaller of its distance and its gap to the newcomer.

That's n rounds, each scanning n pins, so order n squared time and order n space. Every pair of pins could be linked, so the graph is dense, and a plain scan beats a heap. Kruskal's algorithm also works: sort the links, and keep each one that joins two groups.

Grow from one pin, take the cheapest link, update the rest. That's Min Cost to Connect All Points.