All episodes · From a List to Your Map App · Episode 20

The Least Cable to Connect Every House: Minimum Spanning Trees

Pressing play loads the video from YouTube.

Eight houses, twenty-eight possible cables, over two thousand meters if you lay them all. What's the least cable that still reaches every house?
The answer is a tree: connected, no loops, exactly seven cables. Kruskal's method sorts the cables from shortest to longest and skips any that would close a loop: after ten tries, seven cables, 294 meters. Union-find spots those loops in a single step, with each house remembering a leader. Prim's method grows one tree from a single house instead, and lands on the same seven cables and the same 294 meters.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Eight houses need to be wired into one network. Every pair could get its own cable: twenty-eight possible cables. Laying all of them takes over two thousand meters. What's the least cable that still reaches every house? Today: minimum spanning trees.

Every house must be connected, and there should be no loops, because in a loop one cable is always spare. Connected, with no loops: that's a tree. For eight houses, it always takes exactly seven cables.

Kruskal's method is greedy: sort the cables from shortest to longest, and try them in that order. Thirty-seven meters: add it. Thirty-nine: add. Forty would join houses one and three, but they're already connected, so skip it. Keep going. Two more would close loops and get skipped too. After ten tries, seven cables are in: two hundred ninety-four meters.

To spot a loop fast, use union-find: each house remembers a leader, and the same leader means already connected. Adding a cable just points one leader at the other, so two groups become one in a single step.

Prim's method grows a single tree instead: start at house one, and keep adding the shortest cable that reaches a new house. A different order, but the same seven cables, and the same two hundred ninety-four meters.

Shortest first, and skip the loops: here, greedy is guaranteed to give the cheapest network. Next time: when some steps must wait for others, which step comes first? See you there.

Next episode: when some steps must wait for others, which step comes first?

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal