Connecting every stop at minimum total cost
A minimum spanning tree connects all vertices of an undirected weighted graph with the smallest total edge cost. Kruskal’s algorithm considers cheaper links first and skips cycles.
Simple example
The example starts with links already sorted by cost. Take links of cost 2 and 3. All three places are connected. The link of cost 8 would create a cycle. Print 5.
first = [0, 1, 0]
second = [1, 2, 2]
cost = [2, 3, 8]
parent = [0, 1, 2]
total = 0
i = 0
while i < 3
a = first[i]
b = second[i]
while a != parent[a]
a = parent[a]
end
while b != parent[b]
b = parent[b]
end
if a != b
parent[b] = a
total += cost[i]
end
i += 1
end
puts total
5
Everyday examples
Connect three school buildings
Cable runs cost 4, 5 and 12 units. Which two runs connect the triangle most cheaply?
Take the runs costing 4 and 5. The third building already has a connection through the other two.
Skip a redundant short link
A, B and C are already connected. The next cheapest road joins A to C. Should you include it?
Adding the road creates a cycle and adds cost without reaching another place.
Link two garden areas
Plots in the north share one water network. Southern plots share another. There is no pipe between them. Can one tree connect all the plots?
Build one tree in each connected area. Connecting both areas requires at least one new connecting pipe.
Cost and limits
Sorting the edges takes O(E log E). For a disconnected network the same method gives a minimum spanning forest.