Lesson contents

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.

StartA–B:2 B–C:3 A–C:8
Result5
Lesson.groovy
def first = [0, 1, 0]
def second = [1, 2, 2]
def cost = [2, 3, 8]
def parent = [0, 1, 2]
def total = 0
def i = 0
while (i < 3) {
    def a = first[i]
    def b = second[i]
    while (a != parent[a]) {
        a = parent[a]
    }
    while (b != parent[b]) {
        b = parent[b]
    }
    if (a != b) {
        parent[b] = a
        total += cost[i]
    }
    i += 1
}
println(total)
Output
5
Advertisements

Everyday examples

Connect three school buildings

Cable runs cost 4, 5 and 12 units. Which two runs connect the triangle most cheaply?

Start4 5 12
Result9

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?

StartA—B—C
ResultA—B—C

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?

StartA—B / C—D
Result2

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.