Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

Minimum spanning trees

Connecting every vertex as cheaply as possible: spanning trees, the cut property that makes greedy choices safe, Prim’s algorithm with a priority queue, Kruskal’s algorithm with sorting and disjoint sets, and uses from networks to clustering to mazes.

CS61B
Minimum Spanning Trees · Textbook Ch. 22
Swift book
Protocols

A company wants to connect its offices with fiber; each possible link has a cost, and every office must be reachable from every other, directly or through others. Which links should it buy? Not the shortest paths from any one office: that answers a different question. This lesson, like CS61B’s, finds the cheapest way to connect everything, with two algorithms that look different and rest on the same idea.

Spanning trees

For a connected, undirected, weighted graph, a spanning tree is a set of edges that connects all the vertices and has no cycles. With V vertices it always has exactly V − 1 edges: fewer cannot connect everything, and more must contain a cycle. A minimum spanning tree (MST) is a spanning tree whose total edge weight is as small as possible.

An MST is generally not a shortest-path tree. In a square with one heavy diagonal and four light sides, the MST uses three light sides, while the shortest path between opposite corners may be the diagonal.

The cut property

A cut divides the vertices into two nonempty groups. An edge that has one end in each group crosses the cut. The key fact:

For any cut, the lightest edge crossing it belongs to some MST. If all the weights are distinct, it belongs to the MST, which is then unique.

The reason: take an MST that does not contain that lightest crossing edge e. Adding e to it makes a cycle, and the cycle must cross the cut somewhere else, through some other edge f, which is at least as heavy. Replacing f with e keeps everything connected and does not increase the weight.

This justifies being greedy: an algorithm can commit to an edge as soon as it finds a cut where the edge is the lightest crossing, and never reconsider. Both algorithms below are greedy; they differ in which cuts they look at.

Prim’s algorithm

Grow a single tree from any start vertex. The cut is always “the tree” versus “everything else”, so repeatedly add the lightest edge leaving the tree. A priority queue of candidate edges finds it, with lazy deletion as in Dijkstra:

struct Edge {
    let v: Int
    let w: Int
    let weight: Double
}

func prim(vertices: Int, edges: [Edge]) -> [Edge] {
    var adjacent: [[Edge]] = Array(repeating: [], count: vertices)
    for e in edges {
        adjacent[e.v].append(e)
        adjacent[e.w].append(e)
    }
    var inTree = Array(repeating: false, count: vertices)
    var candidates: [Edge] = []            // a simple priority queue: scanned for the minimum
    var tree: [Edge] = []

    func add(_ v: Int) {
        inTree[v] = true
        candidates += adjacent[v].filter { !inTree[$0.v] || !inTree[$0.w] }
    }

    add(0)
    while tree.count < vertices - 1,
          let i = candidates.indices.min(by: { candidates[$0].weight < candidates[$1].weight }) {
        let e = candidates.remove(at: i)
        if inTree[e.v] && inTree[e.w] { continue }       // both ends already in: skip
        tree.append(e)
        add(inTree[e.v] ? e.w : e.v)
    }
    return tree
}

let edges = [Edge(v: 0, w: 1, weight: 4), Edge(v: 0, w: 2, weight: 1), Edge(v: 1, w: 2, weight: 2),
             Edge(v: 1, w: 3, weight: 5), Edge(v: 2, w: 3, weight: 8), Edge(v: 3, w: 4, weight: 3)]
let mst = prim(vertices: 5, edges: edges)
print(mst.map { "\($0.v)-\($0.w)" }, mst.map(\.weight).reduce(0, +))   // ["0-2", "1-2", "1-3", "3-4"] 11.0

It starts at 0, takes the edge of weight 1 to 2, then weight 2 to 1, then weight 5 to 3 (the only other way to reach 3 costs 8), then weight 3 to 4. With a real heap, Prim’s algorithm takes O(E log V), like Dijkstra; in fact the two differ only in the priority: Dijkstra uses the distance from the source, Prim the weight of a single edge.

Kruskal’s algorithm

Kruskal takes a global view: consider all edges from lightest to heaviest, and add each one unless it would make a cycle. The edges chosen form a forest of trees that merge over time, and Lesson 35’s disjoint sets tell in near-constant time whether an edge’s two ends are already connected:

struct Edge {
    let v: Int
    let w: Int
    let weight: Double
}

struct UnionFind {
    private var parent: [Int]
    private var size: [Int]
    init(count: Int) {
        parent = Array(0..<count)
        size = Array(repeating: 1, count: count)
    }
    mutating func find(_ p: Int) -> Int {
        if parent[p] != p { parent[p] = find(parent[p]) }
        return parent[p]
    }
    /// Connects p and q; returns false if they were already connected.
    mutating func connect(_ p: Int, _ q: Int) -> Bool {
        let (a, b) = (find(p), find(q))
        guard a != b else { return false }
        if size[a] < size[b] { parent[a] = b; size[b] += size[a] }
        else { parent[b] = a; size[a] += size[b] }
        return true
    }
}

func kruskal(vertices: Int, edges: [Edge]) -> [Edge] {
    var sets = UnionFind(count: vertices)
    var tree: [Edge] = []
    for e in edges.sorted(by: { $0.weight < $1.weight }) where tree.count < vertices - 1 {
        if sets.connect(e.v, e.w) {
            tree.append(e)
        }
    }
    return tree
}

let edges = [Edge(v: 0, w: 1, weight: 4), Edge(v: 0, w: 2, weight: 1), Edge(v: 1, w: 2, weight: 2),
             Edge(v: 1, w: 3, weight: 5), Edge(v: 2, w: 3, weight: 8), Edge(v: 3, w: 4, weight: 3)]
let mst = kruskal(vertices: 5, edges: edges)
print(mst.map { "\($0.v)-\($0.w)" }, mst.map(\.weight).reduce(0, +))   // ["0-2", "1-2", "3-4", "1-3"] 11.0

The same four edges and the same total, found in a different order: weight 1, 2, 3, then 4 is rejected (0 and 1 are already connected), and 5 completes the tree. Why is each accepted edge safe? When Kruskal accepts e = v–w, take the cut between v’s current tree and everything else: no lighter edge crosses it, since every lighter edge has already been considered, and each was either added or rejected because its ends were in the same tree.

Sorting dominates: Kruskal takes O(E log E), which is O(E log V) since E is at most V². It is simpler to write, and the natural choice when the edges come as a list.

What would Swift print?

let weights = [(0, 1, 7), (1, 2, 3), (0, 2, 5), (2, 3, 1), (1, 3, 2)]
var component = Array(0..<4)
var total = 0
for (v, w, x) in weights.sorted(by: { $0.2 < $1.2 }) {
    let (a, b) = (component[v], component[w])
    if a == b { continue }
    total += x
    for i in component.indices where component[i] == b { component[i] = a }
}
print(total)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer8

In order of weight: 2–3 (1) joins, 1–3 (2) joins, 1–2 (3) would make a cycle, 0–2 (5) joins, and 0–1 (7) would make a cycle. 1 + 2 + 5 = 8. This version tracks components with quick find, which is fine for four vertices.

Put the lines in order

Put the lines in order so the program prints [1, 2, 4].

  1. chosen.append(4)
  2. let weights = [4, 1, 2]
  3. var chosen = weights.sorted()
  4. chosen.removeLast()
  5. print(chosen)

Show the correct program
let weights = [4, 1, 2]
var chosen = weights.sorted()
chosen.removeLast()
chosen.append(4)
print(chosen)

Lab 45: Minimum spanning trees

Q0: What would Swift print?

What would Swift print?

let vertices = 6
let edges = 9
let treeEdges = vertices - 1
let cycleEdges = edges - treeEdges
print(treeEdges, cycleEdges)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer5 4

Every spanning tree of 6 vertices has 5 edges. The other 4 edges each close a cycle with the tree, which is why adding any one of them to an MST must create exactly one cycle, the fact behind the cut property’s proof.

Q1: Checking an MST

Write isSpanningTree(_:vertices:), which checks that a set of edges has V − 1 edges, no cycles, and connects every vertex. Then check, for 100 random graphs, that Prim and Kruskal produce spanning trees of the same total weight.

Show solution
struct Edge {
    let v: Int
    let w: Int
    let weight: Double
}

struct UnionFind {
    private var parent: [Int]
    init(count: Int) { parent = Array(0..<count) }
    mutating func find(_ p: Int) -> Int {
        if parent[p] != p { parent[p] = find(parent[p]) }
        return parent[p]
    }
    mutating func connect(_ p: Int, _ q: Int) -> Bool {
        let (a, b) = (find(p), find(q))
        guard a != b else { return false }
        parent[a] = b
        return true
    }
}

func isSpanningTree(_ tree: [Edge], vertices: Int) -> Bool {
    guard tree.count == vertices - 1 else { return false }
    var sets = UnionFind(count: vertices)
    return tree.allSatisfy { sets.connect($0.v, $0.w) }     // any rejected edge is a cycle
}

func kruskal(vertices: Int, edges: [Edge]) -> [Edge] {
    var sets = UnionFind(count: vertices)
    return edges.sorted { $0.weight < $1.weight }.filter { sets.connect($0.v, $0.w) }
}

func prim(vertices: Int, edges: [Edge]) -> [Edge] {
    var inTree = Array(repeating: false, count: vertices)
    var tree: [Edge] = []
    inTree[0] = true
    while tree.count < vertices - 1 {
        let crossing = edges.filter { inTree[$0.v] != inTree[$0.w] }
        guard let e = crossing.min(by: { $0.weight < $1.weight }) else { break }
        tree.append(e)
        inTree[e.v] = true
        inTree[e.w] = true
    }
    return tree
}

var generator = SystemRandomNumberGenerator()
for _ in 0..<100 {
    let n = Int.random(in: 2...12, using: &generator)
    var edges = (1..<n).map { Edge(v: $0, w: Int.random(in: 0..<$0, using: &generator),
                                   weight: Double.random(in: 0..<10, using: &generator)) }   // a random tree
    for _ in 0..<n {
        let (a, b) = (Int.random(in: 0..<n, using: &generator), Int.random(in: 0..<n, using: &generator))
        if a != b { edges.append(Edge(v: a, w: b, weight: Double.random(in: 0..<10, using: &generator))) }
    }
    let p = prim(vertices: n, edges: edges)
    let k = kruskal(vertices: n, edges: edges)
    assert(isSpanningTree(p, vertices: n) && isSpanningTree(k, vertices: n))
    assert(abs(p.map(\.weight).reduce(0, +) - k.map(\.weight).reduce(0, +)) < 1e-9)
}

This Prim scans all edges at every step for the lightest one crossing the cut, which is slow, Θ(V · E), but it is a direct translation of the cut property, and that makes it a good reference. Starting each random graph from a random tree guarantees that it is connected.

Q2: Clustering

Given points on a line, and a number k, split them into k clusters by building an MST of all pairs (weight = distance) with Kruskal and stopping when k components remain. Return the clusters as sorted arrays.

Show solution
func clusters(_ points: [Double], k: Int) -> [[Double]] {
    let n = points.count
    var parent = Array(0..<n)
    func find(_ p: Int) -> Int {
        var p = p
        while parent[p] != p { p = parent[p] }
        return p
    }
    var pairs: [(Int, Int, Double)] = []
    for i in 0..<n { for j in (i + 1)..<n { pairs.append((i, j, abs(points[i] - points[j]))) } }
    var components = n
    for (i, j, _) in pairs.sorted(by: { $0.2 < $1.2 }) where components > k {
        let (a, b) = (find(i), find(j))
        if a != b {
            parent[a] = b
            components -= 1
        }
    }
    var groups: [Int: [Double]] = [:]
    for i in 0..<n { groups[find(i), default: []].append(points[i]) }
    return groups.values.map { $0.sorted() }.sorted { $0[0] < $1[0] }
}

let points = [1.0, 1.5, 2.0, 10.0, 10.2, 20.0, 21.0]
assert(clusters(points, k: 3) == [[1.0, 1.5, 2.0], [10.0, 10.2], [20.0, 21.0]])
assert(clusters(points, k: 1).count == 1)

Stopping Kruskal early leaves out exactly the heaviest MST edges, the largest gaps between groups. This is called single-linkage clustering, and it is the simplest form of hierarchical clustering.

Q3: A random maze

Generate a maze on a grid of rows × columns cells: list every wall between two adjacent cells, shuffle the list (random weights), and knock down a wall whenever its two cells are not yet connected, as Kruskal would. Check that exactly rows × columns − 1 walls come down and that every cell is reachable.

Show solution
struct Wall: Hashable {
    let a: Int
    let b: Int
}

func maze(rows: Int, columns: Int) -> Set<Wall> {
    let n = rows * columns
    var parent = Array(0..<n)
    func find(_ p: Int) -> Int {
        var p = p
        while parent[p] != p {
            parent[p] = parent[parent[p]]      // path halving
            p = parent[p]
        }
        return p
    }
    var walls: [Wall] = []
    for r in 0..<rows {
        for c in 0..<columns {
            let cell = r * columns + c
            if c + 1 < columns { walls.append(Wall(a: cell, b: cell + 1)) }
            if r + 1 < rows { walls.append(Wall(a: cell, b: cell + columns)) }
        }
    }
    var open: Set<Wall> = []
    for wall in walls.shuffled() {
        let (x, y) = (find(wall.a), find(wall.b))
        if x != y {
            parent[x] = y
            open.insert(wall)
        }
    }
    return open
}

let (rows, columns) = (10, 15)
let passages = maze(rows: rows, columns: columns)
assert(passages.count == rows * columns - 1)

var adjacent: [Int: [Int]] = [:]
for wall in passages {
    adjacent[wall.a, default: []].append(wall.b)
    adjacent[wall.b, default: []].append(wall.a)
}
var seen: Set = [0]
var stack = [0]
while let v = stack.popLast() {
    for w in adjacent[v, default: []] where seen.insert(w).inserted { stack.append(w) }
}
assert(seen.count == rows * columns)

The passages form a spanning tree of the cells, so there is exactly one route between any two cells: a “perfect” maze. Shuffling plays the role of random weights; since all edges are otherwise equal, any spanning tree is minimal, and the shuffle chooses one at random.

Q4 (optional): Maximum spanning tree

Find a spanning tree with the largest total weight. How much of Kruskal needs to change? Use it to find, in a network where edges are link capacities, the path between two vertices whose weakest link is as strong as possible.

Show solution
struct Edge {
    let v: Int
    let w: Int
    let capacity: Int
}

func maximumSpanningTree(vertices: Int, edges: [Edge]) -> [Edge] {
    var parent = Array(0..<vertices)
    func find(_ p: Int) -> Int {
        var p = p
        while parent[p] != p { p = parent[p] }
        return p
    }
    var tree: [Edge] = []
    for e in edges.sorted(by: { $0.capacity > $1.capacity }) {      // heaviest first
        let (a, b) = (find(e.v), find(e.w))
        if a != b {
            parent[a] = b
            tree.append(e)
        }
    }
    return tree
}

func bottleneck(from s: Int, to t: Int, in tree: [Edge]) -> Int? {
    var adjacent: [Int: [(Int, Int)]] = [:]
    for e in tree {
        adjacent[e.v, default: []].append((e.w, e.capacity))
        adjacent[e.w, default: []].append((e.v, e.capacity))
    }
    var best: [Int: Int] = [s: .max]
    var stack = [s]
    while let v = stack.popLast() {
        for (w, capacity) in adjacent[v, default: []] where best[w] == nil {
            best[w] = min(best[v]!, capacity)
            stack.append(w)
        }
    }
    return best[t]
}

let links = [Edge(v: 0, w: 1, capacity: 5), Edge(v: 1, w: 3, capacity: 5), Edge(v: 0, w: 2, capacity: 9),
             Edge(v: 2, w: 3, capacity: 2), Edge(v: 0, w: 3, capacity: 1)]
let tree = maximumSpanningTree(vertices: 4, edges: links)
assert(tree.map(\.capacity).reduce(0, +) == 19)
assert(bottleneck(from: 0, to: 3, in: tree) == 5)       // through 1, not the direct link or 2

Only the sort order changes: the cut property works the same with “heaviest crossing edge”. And the path between two vertices in a maximum spanning tree is always one whose weakest link is as strong as possible, which is the best route for, say, the widest vehicle through a road network or the most bandwidth through a network.

What’s next

Next lesson: directed graphs without cycles, putting tasks in an order that respects their dependencies, and solving one problem by turning it into another.