Boss lesson · Unit 04
Minimum spanning tree
Connect everything for the least total cost
What you practise
- Kruskal with union-find
- Prim's idea
Try a question from this lesson
Pick one
Four villages need cable. The possible links and their costs: A–B 1, B–C 2, A–C 3, C–D 4, B–D 5. What is the least total cost that connects all four?
Correct answer
7
Why
Take A–B and B–C for 3. A–C would join two villages that are already connected, so it is wasted money. C–D brings in the last village: 1 + 2 + 4 = 7. The three cheapest links total 6, but they leave D out.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Kruskal: cheapest edge first
Kruskal's algorithm builds a minimum spanning tree greedily. Look at the edges from cheapest to dearest, and keep each one unless it would close a cycle.
Step one is a sort. Storing each edge with its weight first makes that easy.
edges = [(3, 0, 2), (1, 0, 1), (4, 2, 3),
(2, 1, 2), (5, 1, 3)]
# tuples sort by their first item
edges.sort()
for w, a, b in edges:
print(w, a, b)const edges = [
[3, 0, 2], [1, 0, 1], [4, 2, 3],
[2, 1, 2], [5, 1, 3],
];
// sort by the first item: the weight
edges.sort((x, y) => x[0] - y[0]);
for (const [w, a, b] of edges) {
console.log(w, a, b);
}const edges = [
[3, 0, 2], [1, 0, 1], [4, 2, 3],
[2, 1, 2], [5, 1, 3],
];
// sort by the first item: the weight
edges.sort((x, y) => x[0] - y[0]);
for (const [w, a, b] of edges) {
console.log(w, a, b);
}JavaScript noteWithout a comparator, sort() compares items as text. (x, y) => x[0] - y[0] orders the edges by weight.
TypeScript noteWithout a comparator, sort() compares items as text. (x, y) => x[0] - y[0] orders the edges by weight.
Concept
Prim: grow one tree
Prim's algorithm starts at one node and grows a single tree. A min-heap holds the edges leaving the tree; take the cheapest.
If its far end is already in the tree, skip it. Otherwise add that node, pay for the edge and push the new node's edges.
from heapq import heappush, heappop
def prim(adj):
seen = set()
heap = [(0, 0)] # (weight, node)
total = 0
while heap:
w, u = heappop(heap)
if u in seen:
continue
seen.add(u)
total += w
for v, wv in adj[u]:
heappush(heap, (wv, v))
return totalfunction prim(adj) {
const seen = new Set();
const heap = new MinHeap();
heap.push([0, 0]); // [weight, node]
let total = 0;
while (heap.size > 0) {
const [w, u] = heap.pop();
if (seen.has(u)) continue;
seen.add(u);
total += w;
for (const [v, wv] of adj[u]) {
heap.push([wv, v]);
}
}
return total;
}function prim(adj: Hop[][]) {
const seen = new Set<number>();
const heap = new MinHeap();
heap.push([0, 0]); // [weight, node]
let total = 0;
while (heap.size > 0) {
const [w, u] = heap.pop();
if (seen.has(u)) continue;
seen.add(u);
total += w;
for (const [v, wv] of adj[u]) {
heap.push([wv, v]);
}
}
return total;
}Python noteThe shape is Dijkstra's, with one change: the heap key is the weight of a single edge, not a distance from the start.
JavaScript noteJavaScript has no built-in heap. MinHeap is the class from the Trees & Heaps roadmap: push adds a pair and pop removes the pair with the smallest first item.
TypeScript noteMinHeap is the class from the Trees & Heaps roadmap: pop removes the pair with the smallest first item. Hop is an alias for [number, number].
9 more exercises in the app
- 4× multiple choice
- 1× type the answer
- 1× order the lines
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.