Chapters

Hide chapters

Data Structures & Algorithms in Swift

Fifth Edition · iOS 18 · Swift 6.0 · Xcode 16.2

43. Dijkstra’s Algorithm Challenges
Written by Vincent Ngo

Challenge 1: Step-by-step diagram

Given the following graph, step through Dijkstra’s algorithm to produce the shortest path to every other vertex starting from vertex A. Provide the final table of the paths as shown in the previous chapter.

21 8 2 1 12 9 2 B D E C A

Challenge 2: Find all the shortest paths

Add a method to class Dijkstra that returns a dictionary of all the shortest paths to all vertices given a starting vertex. Here’s the method signature to get you started:

public func getAllShortestPath(from source: Vertex<T>)
                               -> [Vertex<T> : [Edge<T>]] {
    var pathsDict = [Vertex<T> : [Edge<T>]]()

    // Implement Solution Here

    return pathsDict
}

Solutions

Solution to Challenge 1

Start A 10 B 21 A 21 A 12 A nil 11 C 9 B 1 A 1 A 1 A 1 A 1 A 9 B 9 B 9 B 11 C 11 C 10 B 10 B 10 B B B C D E C D E

  • Path to B: A - (1) - B
  • Path to C: A - (1) - B - (8) - C
  • Path to D: A - (1) - B - (9) - D
  • Path to E: A - (1) - B - (8) - C - (2) - E

Solution to Challenge 2

This function is part of Dijkstra.swift. To get the shortest paths from the source vertex to every other vertex in the graph, do the following:

public func getAllShortestPath(from source: Vertex<T>)
                               -> [Vertex<T> : [Edge<T>]] {
  var pathsDict = [Vertex<T> : [Edge<T>]]() // 1
  let pathsFromSource = shortestPath(from: source) // 2
  for vertex in graph.vertices { // 3
    let path = shortestPath(to: vertex, paths: pathsFromSource)
    pathsDict[vertex] = path
  }
  return pathsDict // 4
}
  1. The dictionary stores the path to every vertex from the source vertex.
  2. Perform Dijkstra’s algorithm to find all the paths from the source vertex.
  3. For every vertex in the graph, generate the list of edges between the source vertex to every vertex in the graph.
  4. Return the dictionary of paths.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.