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

Shortest paths: Dijkstra and A*

Weighted graphs and why BFS is not enough, edge relaxation, Dijkstra’s algorithm with a priority queue and its O(E log V) cost, why negative edges break it, and A* search guided by an admissible heuristic.

CS61B
Shortest Paths · Textbook Ch. 21
Swift book
Generics
Documentation
Swift Collections

Breadth-first search finds the path with the fewest edges. But roads have lengths, flights have prices, and network links have delays: the path with the fewest edges is not the cheapest. This lesson, following CS61B’s shortest paths lecture, adds weights to edges and builds the algorithm that every mapping app descends from, then makes it faster with a good guess about where the goal is.

Weighted graphs

In a weighted graph, each edge carries a number, its weight. The length of a path is the sum of its edge weights, and a shortest path is one with the least total weight. Store weighted edges in the adjacency lists:

struct Edge {
    let to: Int
    let weight: Double
}

var adjacent: [[Edge]]      // adjacent[v] lists the edges leaving v

BFS fails here because it explores by number of edges. A direct edge of weight 10 is found before a path of two edges of weight 1 each, and never improved.

Relaxation

Every shortest-path algorithm in this course is built on one operation. Keep, for every vertex, the best known distance from the source, distTo, starting at infinity everywhere except the source, and the last edge on that best path, edgeTo. To relax an edge v → w with weight x is to ask: is going through v better than the best known way to reach w?

if distTo[v] + x < distTo[w] {
    distTo[w] = distTo[v] + x
    edgeTo[w] = v
}

The algorithms differ only in the order in which they relax edges.

Dijkstra’s algorithm

Edsger Dijkstra’s idea is to visit vertices in order of their distance from the source: always take the unvisited vertex with the smallest distTo, mark it done, and relax all its edges. A priority queue (Lesson 41) finds that vertex quickly:

struct Edge {
    let to: Int
    let weight: Double
}

struct MinHeap<Element> {
    private var items: [Element] = []
    private let less: (Element, Element) -> Bool
    init(by less: @escaping (Element, Element) -> Bool) { self.less = less }
    var isEmpty: Bool { items.isEmpty }
    mutating func insert(_ x: Element) {
        items.append(x)
        var i = items.count - 1
        while i > 0, less(items[i], items[(i - 1) / 2]) { items.swapAt(i, (i - 1) / 2); i = (i - 1) / 2 }
    }
    mutating func pop() -> Element? {
        guard !items.isEmpty else { return nil }
        items.swapAt(0, items.count - 1)
        let top = items.removeLast()
        var i = 0
        while true {
            let (l, r) = (2 * i + 1, 2 * i + 2)
            var best = i
            if l < items.count, less(items[l], items[best]) { best = l }
            if r < items.count, less(items[r], items[best]) { best = r }
            if best == i { return top }
            items.swapAt(i, best)
            i = best
        }
    }
}

func dijkstra(_ adjacent: [[Edge]], from source: Int) -> (distTo: [Double], edgeTo: [Int?]) {
    var distTo = Array(repeating: Double.infinity, count: adjacent.count)
    var edgeTo = [Int?](repeating: nil, count: adjacent.count)
    var done = Array(repeating: false, count: adjacent.count)
    var queue = MinHeap<(vertex: Int, distance: Double)> { $0.distance < $1.distance }
    distTo[source] = 0
    queue.insert((source, 0))
    while let (v, _) = queue.pop() {
        if done[v] { continue }                // an outdated entry: skip it
        done[v] = true
        for edge in adjacent[v] where distTo[v] + edge.weight < distTo[edge.to] {
            distTo[edge.to] = distTo[v] + edge.weight
            edgeTo[edge.to] = v
            queue.insert((edge.to, distTo[edge.to]))
        }
    }
    return (distTo, edgeTo)
}

//      0 ──5── 1
//      │  ╲    │
//      1   9   1
//      │     ╲ │
//      2 ──1── 3 ──2── 4
let edges: [(Int, Int, Double)] = [(0, 1, 5), (0, 2, 1), (0, 3, 9), (1, 3, 1), (2, 3, 1), (3, 4, 2)]
var adjacent: [[Edge]] = Array(repeating: [], count: 5)
for (v, w, x) in edges {
    adjacent[v].append(Edge(to: w, weight: x))
    adjacent[w].append(Edge(to: v, weight: x))
}
let (distTo, edgeTo) = dijkstra(adjacent, from: 0)
var path = [4]
while let previous = edgeTo[path.last!] { path.append(previous) }
print(distTo, Array(path.reversed()))   // [0.0, 3.0, 1.0, 2.0, 4.0] [0, 2, 3, 4]

The direct edge 0–3 of weight 9 loses to the path 0–2–3 of weight 2, and vertex 1 is reached more cheaply through 3 than directly. Swift’s Double.infinity behaves as it should: adding to it gives infinity, and every finite number is less.

Lazy deletion

When a vertex’s distance improves, it is inserted into the queue again, and the old entry stays there. When an old entry is popped later, the vertex is already done, and the entry is skipped. CS61B’s version instead changes the priority of the existing entry, which needs a heap that can find an item’s position; lazy deletion is simpler, and the queue holds at most E entries.

Why it works, and what it costs

When Dijkstra takes a vertex v from the queue, distTo[v] is final. Any other path to v would have to leave the set of done vertices somewhere, through a vertex whose distance is at least distTo[v], since v was the smallest; with non-negative weights, continuing from there cannot make it any shorter.

Each edge is relaxed once, from its source when that vertex is done, and each relaxation may insert into the heap, at O(log E) = O(log V) each. So Dijkstra’s algorithm is O(E log V).

What would Swift print?

let inf = Double.infinity
var distTo = [0.0, inf, inf]
var edgeTo: [Int?] = [nil, nil, nil]
func relax(_ v: Int, _ w: Int, _ x: Double) {
    if distTo[v] + x < distTo[w] {
        distTo[w] = distTo[v] + x
        edgeTo[w] = v
    }
}
relax(0, 2, 10)
relax(0, 1, 3)
relax(1, 2, 4)
relax(2, 1, 1)
print(distTo, edgeTo[2]!)

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

Show answer and explanation

Answer[0.0, 3.0, 7.0] 1

Relaxing 0 → 2 sets 2’s distance to 10; then 0 → 1 gives 1 a distance of 3, and 1 → 2 improves 2 to 3 + 4 = 7, through 1. Relaxing 2 → 1 would give 1 a distance of 8, which is worse than 3, so nothing changes.

Negative weights

The argument above assumed that continuing a path never makes it shorter. With a negative edge weight, that fails, and so does Dijkstra: it can mark a vertex done too early. Lab Q2 constructs an example. Negative weights do occur, for instance in currency exchange rates taken as logarithms, and need a slower algorithm, Bellman–Ford, or, for graphs without cycles, the method of Lesson 47.

A*: searching toward a goal

Dijkstra explores in every direction, like a ripple on water. When only the path to one goal is wanted, most of that work is wasted. Driving from San Francisco to Los Angeles, Dijkstra would explore Oregon before reaching the goal.

A* (pronounced “A star”) adds a heuristic: an estimate h(v) of the remaining distance from v to the goal. It takes vertices from the queue in order of distTo[v] + h(v), the known distance so far plus the estimated distance to go, so it favors vertices that seem to lie toward the goal:

struct Point: Hashable {
    let row: Int
    let column: Int
}

/// Shortest path length on a grid, moving up, down, left, and right, where
/// "#" is a wall. Returns the length and the number of cells expanded.
func search(_ grid: [String], from start: Point, to goal: Point, heuristic: (Point) -> Int) -> (length: Int?, expanded: Int) {
    let cells = grid.map(Array.init)
    var distance = [start: 0]
    var done: Set<Point> = []
    var frontier = [(point: start, priority: heuristic(start))]
    while let index = frontier.indices.min(by: { frontier[$0].priority < frontier[$1].priority }) {
        let current = frontier.remove(at: index).point
        if done.contains(current) { continue }
        done.insert(current)
        if current == goal { return (distance[current], done.count) }
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let next = Point(row: current.row + dr, column: current.column + dc)
            guard cells.indices.contains(next.row), cells[next.row].indices.contains(next.column),
                  cells[next.row][next.column] != "#" else { continue }
            let d = distance[current]! + 1
            if d < distance[next, default: .max] {
                distance[next] = d
                frontier.append((next, d + heuristic(next)))
            }
        }
    }
    return (nil, done.count)
}

let grid = Array(repeating: String(repeating: ".", count: 30), count: 30)
let start = Point(row: 15, column: 0)
let goal = Point(row: 15, column: 29)
let manhattan = { (p: Point) in abs(p.row - goal.row) + abs(p.column - goal.column) }
let dijkstraResult = search(grid, from: start, to: goal) { _ in 0 }
let aStarResult = search(grid, from: start, to: goal, heuristic: manhattan)
print(dijkstraResult.length!, aStarResult.length!, aStarResult.expanded < dijkstraResult.expanded / 5)   // 29 29 true

With h = 0, A* is Dijkstra. With the Manhattan distance, the number of steps to the goal ignoring walls, it finds the same 29-step path while expanding a small fraction of the cells. (The frontier here is an array scanned for its minimum, to keep the example short; a real implementation uses a heap.)

A* is guaranteed to find a shortest path if the heuristic never overestimates the true remaining distance; such a heuristic is called admissible. The Manhattan distance is admissible on a grid, because walls can only make the trip longer. A heuristic that sometimes guesses too high can lead A* to accept a path that is not the shortest. The best heuristic is the largest one that is still admissible: h equal to the true distance would lead A* straight to the goal.

Put the lines in order

Put the lines in order so the program prints 7.0.

  1. if distTo[1] + weight < distTo[2] {
  2. var distTo = [0.0, 5.0, Double.infinity]
  3. let weight = 2.0
  4. distTo[2] = distTo[1] + weight
  5. }
  6. print(distTo[2])

Show the correct program
var distTo = [0.0, 5.0, Double.infinity]
let weight = 2.0
if distTo[1] + weight < distTo[2] {
    distTo[2] = distTo[1] + weight
}
print(distTo[2])

Lab 44: Shortest paths

Q0: What would Swift print?

What would Swift print?

let inf = Double.infinity
print(inf + 1 == inf, 5 < inf, min(3.0, inf), inf - inf == inf)

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

Show answer and explanation

Answertrue true 3.0 false

Infinity absorbs additions and compares greater than every finite number, which makes it a natural “not reached yet” distance. But infinity minus infinity is not a number (NaN), and NaN is not equal to anything, not even itself.

Q1: Paths out of Dijkstra

Using the lesson’s dijkstra, write shortestPath(_:from:to:), which returns the list of vertices on a shortest path and its total weight, or nil if the target is unreachable. Test it on a directed graph where the target cannot be reached.

Show solution
struct Edge {
    let to: Int
    let weight: Double
}

func dijkstra(_ adjacent: [[Edge]], from source: Int) -> (distTo: [Double], edgeTo: [Int?]) {
    var distTo = Array(repeating: Double.infinity, count: adjacent.count)
    var edgeTo = [Int?](repeating: nil, count: adjacent.count)
    var done = Array(repeating: false, count: adjacent.count)
    var queue: [(vertex: Int, distance: Double)] = [(source, 0)]
    distTo[source] = 0
    while let i = queue.indices.min(by: { queue[$0].distance < queue[$1].distance }) {
        let v = queue.remove(at: i).vertex
        if done[v] { continue }
        done[v] = true
        for e in adjacent[v] where distTo[v] + e.weight < distTo[e.to] {
            distTo[e.to] = distTo[v] + e.weight
            edgeTo[e.to] = v
            queue.append((e.to, distTo[e.to]))
        }
    }
    return (distTo, edgeTo)
}

func shortestPath(_ adjacent: [[Edge]], from s: Int, to t: Int) -> (path: [Int], length: Double)? {
    let (distTo, edgeTo) = dijkstra(adjacent, from: s)
    guard distTo[t] < .infinity else { return nil }
    var path = [t]
    while let previous = edgeTo[path.last!] { path.append(previous) }
    return (path.reversed(), distTo[t])
}

// A directed graph: 0 → 1 (4), 0 → 2 (1), 2 → 1 (2), 1 → 3 (5), and 4 has no incoming edges.
let adjacent: [[Edge]] = [
    [Edge(to: 1, weight: 4), Edge(to: 2, weight: 1)],
    [Edge(to: 3, weight: 5)],
    [Edge(to: 1, weight: 2)],
    [],
    [Edge(to: 0, weight: 1)],
]
let result = shortestPath(adjacent, from: 0, to: 3)!
assert(result.path == [0, 2, 1, 3] && result.length == 8)
assert(shortestPath(adjacent, from: 0, to: 4) == nil)

The queue here is an array scanned for its minimum, which makes each step Θ(V) and the whole algorithm Θ(V²) rather than O(E log V). For dense graphs, that is actually fine, and a heap only helps when the graph is sparse.

Q2: A negative edge

Construct a small directed graph with one negative edge weight, and no negative cycle, on which Dijkstra’s algorithm returns a wrong distance. Explain which step goes wrong.

Show solution
struct Edge {
    let to: Int
    let weight: Double
}

func dijkstra(_ adjacent: [[Edge]], from source: Int) -> [Double] {
    var distTo = Array(repeating: Double.infinity, count: adjacent.count)
    var done = Array(repeating: false, count: adjacent.count)
    var queue: [(vertex: Int, distance: Double)] = [(source, 0)]
    distTo[source] = 0
    while let i = queue.indices.min(by: { queue[$0].distance < queue[$1].distance }) {
        let v = queue.remove(at: i).vertex
        if done[v] { continue }
        done[v] = true
        for e in adjacent[v] where !done[e.to] && distTo[v] + e.weight < distTo[e.to] {
            distTo[e.to] = distTo[v] + e.weight
            queue.append((e.to, distTo[e.to]))
        }
    }
    return distTo
}

// 0 → 1 (weight 2), 0 → 2 (weight 5), 2 → 1 (weight −4)
let adjacent: [[Edge]] = [
    [Edge(to: 1, weight: 2), Edge(to: 2, weight: 5)],
    [],
    [Edge(to: 1, weight: -4)],
]
let distTo = dijkstra(adjacent, from: 0)
assert(distTo[1] == 2)          // Dijkstra's answer
let trueDistance = 5.0 - 4.0    // the path 0 → 2 → 1
assert(distTo[1] != trueDistance)

Dijkstra takes vertex 1 out of the queue with distance 2 and marks it done, because 2 is smaller than vertex 2’s distance, 5. Its reasoning is that any other path to 1 must pass through a vertex at distance at least 2 and can only get longer. The edge 2 → 1 with weight −4 breaks that: the path through 2 ends up shorter, at 1, but 1 is already done.

Q3: Cheapest flights with a stop limit

Flights are directed edges with prices. Find the cheapest price from s to t using at most k stops, where Dijkstra alone does not work (the cheapest path may have too many stops). Relax every edge k + 1 times, using the distances from the previous round each time.

Show solution
func cheapest(_ flights: [(from: Int, to: Int, price: Int)], cities: Int, from s: Int, to t: Int, stops k: Int) -> Int? {
    var cost = Array(repeating: Int.max, count: cities)
    cost[s] = 0
    for _ in 0...k {
        var next = cost                                  // this round's results
        for flight in flights where cost[flight.from] != .max {
            next[flight.to] = min(next[flight.to], cost[flight.from] + flight.price)
        }
        cost = next
    }
    return cost[t] == .max ? nil : cost[t]
}

let flights = [(from: 0, to: 1, price: 100), (from: 1, to: 2, price: 100), (from: 2, to: 3, price: 100),
               (from: 0, to: 3, price: 500), (from: 0, to: 2, price: 250)]
assert(cheapest(flights, cities: 4, from: 0, to: 3, stops: 2) == 300)
assert(cheapest(flights, cities: 4, from: 0, to: 3, stops: 1) == 350)
assert(cheapest(flights, cities: 4, from: 0, to: 3, stops: 0) == 500)

After round i, cost[v] is the cheapest way to reach v with at most i flights. Reading only the previous round’s cost while writing next is what keeps the flight count honest; updating in place could use a flight found earlier in the same round. With enough rounds, this is the Bellman–Ford algorithm, which also handles negative weights.

Q4: A* with walls

Add walls to the lesson’s 30 × 30 grid, a vertical wall from row 5 to row 25 in column 15, and compare how many cells Dijkstra and A* expand. Check that both find the same length.

Show solution
struct Point: Hashable {
    let row: Int
    let column: Int
}

func search(_ cells: [[Character]], from start: Point, to goal: Point, heuristic: (Point) -> Int) -> (length: Int?, expanded: Int) {
    var distance = [start: 0]
    var done: Set<Point> = []
    var frontier = [(point: start, priority: heuristic(start))]
    while let index = frontier.indices.min(by: { frontier[$0].priority < frontier[$1].priority }) {
        let current = frontier.remove(at: index).point
        if done.contains(current) { continue }
        done.insert(current)
        if current == goal { return (distance[current], done.count) }
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let next = Point(row: current.row + dr, column: current.column + dc)
            guard cells.indices.contains(next.row), cells[next.row].indices.contains(next.column),
                  cells[next.row][next.column] != "#" else { continue }
            let d = distance[current]! + 1
            if d < distance[next, default: .max] {
                distance[next] = d
                frontier.append((next, d + heuristic(next)))
            }
        }
    }
    return (nil, done.count)
}

var cells = Array(repeating: Array(repeating: Character("."), count: 30), count: 30)
for row in 5...25 { cells[row][15] = "#" }
let start = Point(row: 15, column: 0)
let goal = Point(row: 15, column: 29)
let manhattan = { (p: Point) in abs(p.row - goal.row) + abs(p.column - goal.column) }
let plain = search(cells, from: start, to: goal) { _ in 0 }
let guided = search(cells, from: start, to: goal, heuristic: manhattan)
assert(plain.length == guided.length && plain.length == 51)
assert(guided.expanded < plain.expanded)

The wall covers rows 5 to 25, so the path must climb to row 4 (or down to row 26) and come back: 29 + 2 × 11 = 51 steps. A* still expands fewer cells, about 670 against about 880, but its advantage has shrunk, because the heuristic points straight at the wall. Heuristics are guesses; obstacles are where they are wrong, and where A* falls back toward Dijkstra.

What’s next

Shortest paths connect one source to everything. Next lesson: the cheapest way to connect everything to everything, minimum spanning trees.