Chapters

Hide chapters

Data Structures & Algorithms in Swift

Fifth Edition · iOS 18 · Swift 6.0 · Xcode 16.2

42. Dijkstra’s Algorithm
Written by Vincent Ngo

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Have you ever used the Google or Apple Maps app to find the shortest distance or fastest time from one place to another? Dijkstra’s algorithm is particularly useful in GPS networks to help find the shortest path between two places.

Dijkstra’s algorithm is a greedy algorithm. A greedy algorithm constructs a solution step-by-step, and it picks the most optimal path at every step in isolation. It misses solutions where some steps might cost more, but the overall cost is lower. Nevertheless, it usually arrives at a pretty good solution very quickly.

Dijkstra’s algorithm finds the shortest paths between vertices in either directed or undirected graphs. Given a vertex in a graph, the algorithm will find all shortest paths from the starting vertex.

Some other applications of Dijkstra’s algorithm include:

  1. Communicable disease transmission: Discover where biological diseases are spreading the fastest.
  2. Telephone networks: Routing calls to highest-bandwidth paths available in the network.
  3. Mapping: Finding the shortest and fastest paths for travelers.

Example

All the graphs you have looked at thus far have been undirected. Let’s change it up a little and work with a directed graph! Imagine the directed graph below represents a GPS network:

The vertices represent physical locations, and the edges represent one-way paths of a given cost between locations.

3 9 2 8 2 1 1 3 1 8 5 2 3 1 H G C E B F A D

In Dijkstra’s algorithm, you first choose a starting vertex since the algorithm needs a starting point to find a path to the rest of the nodes in the graph. Assume the starting vertex you pick is vertex A.

First pass

3 9 2 8 2 1 1 3 1 8 5 2 3 1 A H F B D E C G 8 A 9 A 1 A nil nil nil nil B C D E F G H Start A

Second pass

8 A 9 A 1 A nil nil nil nil B C D E F G H Start A

3 9 1 1 4 4 9 6 0 7 0 1 4 7 E V X V D E T J Glawl O 6 A 1 U vub rim xat vav 4 I 3 A kiv bin yic 3 S 6 A 4 I F S J P O H R P

Third pass

Start A 8 A 9 A nil nil nil nil 8 A 9 A nil nil nil 4 G 1 A 1 A B G C D E F G H

0 4 9 1 7 1 9 8 9 8 0 9 7 6 E Y M S Q A X Yzamf U 9 E 4 A xox may fuv jut 0 E 7 O bid pud fog 7 H 2 K 3 U 7 I 6 K 6 I 5 B bih sut 3 O N M R W S O Z Z M M

Fourth pass

Start A 8 A 9 A nil nil nil nil 8 A 9 A nil nil nil 4 G 4 G 1 A 1 A 7 C 9 A 5 C nil nil 1 A B G C C D E F G H

0 8 0 8 0 6 2 4 0 1 1 0 2 5 U W P G Q X Cxewl U 8 A 9 I yas dip goq xiw 5 E 5 O nut baj nob 8 N 8 B 5 I 4 I 6 P 5 U jij qiq 3 U 1 U 6 I 1 O xib 3 S 3 U 7 D 3 F B G Q U H C E P Z W G A

Fifth pass

Start A 8 A 9 A nil nil nil nil 8 A 9 A nil nil nil 4 G 4 G 1 A 1 A 7 C 9 A nil nil 1 A 6 E 9 A 7 E nil 4 G 1 A 5 C 5 C B G C E C D E F G H

Zgipf O 8 O 5 I jix vuc pic fit 6 U 3 A mow liw fuf 7 G 2 P 4 A 1 U 0 H 0 E yek lul 3 O 1 I 7 E 0 A yay 6 Q 1 E 2 N 3 A 5 E kes 5 I 1 Y 2 I 0 B 4 V S P C I K Q Z A J V Z 7 9 4 0 1 6 9 6 7 4 4 4 4 0 O C C Y C M B U

Sixth pass

Start A 8 A 9 A nil nil nil nil 8 A 9 A nil nil nil 4 G 4 G 1 A 1 A 7 C 9 A nil nil 1 A 6 E 9 A 7 E nil 4 G 1 A 5 C 9 A 7 E nil 6 E 4 G 1 A 5 C 5 C B G C E B C D E F G H

5 4 1 4 2 0 3 7 6 2 0 5 2 8 A M J Z Q A R Q Rfifp U 2 I 7 E hoc luq qab bam 1 I 9 I ruk bor hay 3 X 2 Y 9 A 2 A 5 Z 9 E 2 E 2 E zuc pux jin 1 U 3 A 7 I 1 O 0 A 1 E 1 E cuy 6 B 5 R 3 V 7 U 1 O 4 I 2 A 5 G 1 S 7 X 5 N Z Q X A L V F Y E Z C X fav

Seventh pass

Start A 8 A 9 A nil nil nil nil 8 A 9 A nil nil nil 4 G 4 G 1 A 1 A 7 C 9 A 7 E 9 A nil nil nil 1 A 6 E 6 E 6 E 9 A 9 A 7 E nil 4 G 4 G 4 G 7 E 1 A 1 A 1 A 5 C 5 C 5 C 5 C B G C E B D C D E F G H nil

Fdutb A 2 O 2 U des bey tuz qaz 3 A 0 A dak vif raz 8 X 5 Q 2 U 8 A 4 C 7 U 2 I 3 U nat hax tiv lup 0 U 5 O 8 O 6 I 6 O 7 I 6 E 9 U roh 8 W 3 J 5 R 4 R 4 E 8 U 4 E 2 I 4 U 6 E 9 W 1 L 5 F 7 L 0 E 8 J C J H I L M Y G W U T W N 5 0 2 0 3 2 6 0 4 1 5 1 3 1 I V L N E N V Y vaf

Eighth pass

You have covered every vertex except for H. H has two outgoing edges to G and F. However, there is no path from A to H. Because there is no path, the whole column for H is nil.

Mmurl I 9 U 2 A nen gal vef wow 3 A 5 O gil nun vam 6 V 2 D 6 U 6 A 9 Y 8 E 7 A 5 O raf yoz dar cum 2 U 9 A 5 I 9 I 7 I 3 A 8 E 4 I xas 3 W 5 B 0 N 4 C 3 U 0 E 2 A 5 U 8 O 9 U 0 R 1 F 8 R 8 F 0 O 9 K J Y G I K W R C M O H V F 4 9 7 7 3 0 4 9 8 0 4 1 3 4 O T Z Q O D L H juj

Prigr U 1 A 9 R 6 I 6 E 6 E kor gic xol nak xep qaf mic rom 3 E 8 I moq fec zut 8 D 7 Y 9 G 4 U 7 O 7 I 6 I sob xes 3 X 1 W 5 Z 3 E 9 I 5 U 8 D 8 Y 0 P 6 A 3 A 0 A 5 I 3 E 5 E 0 O 0 A 0 U 9 E 3 N 3 O 3 V M N D I K Y X Y R U V C P 4 8 7 9 7 8 0 6 2 1 0 4 7 3 S D O A G N X D

Implementation

Open up the starter playground for this chapter. This playground comes with an adjacency list graph and a priority queue, which you will use to implement Dijkstra’s algorithm.

public enum Visit<T: Hashable> {
  case start // 1
  case edge(Edge<T>) // 2
}
public class Dijkstra<T: Hashable> {

  public typealias Graph = AdjacencyList<T>
  let graph: Graph

  public init(graph: Graph) {
    self.graph = graph
  }
}

Helper methods

Before building Dijkstra, let’s create some helper methods that will help create the algorithm.

Tracing back to the start

C to G to A G 3 9 2 8 2 1 1 3 1 8 5 2 3 1 H C E D B A F

private func route(to destination: Vertex<T>,
                   with paths: [Vertex<T> : Visit<T>]) -> [Edge<T>] {
  var vertex = destination // 1
  var path: [Edge<T>] = [] // 2

  while let visit = paths[vertex], case .edge(let edge) = visit { // 3
    path = [edge] + path // 4
    vertex = edge.source // 5
  }
  return path // 6
}

Calculating total distance

Total distance = 4 A G 3 1 C

private func distance(to destination: Vertex<T>,
                      with paths: [Vertex<T> : Visit<T>]) -> Double {
  let path = route(to: destination, with: paths) // 1
  let distances = path.compactMap { $0.weight } // 2
  return distances.reduce(0.0, +) // 3
}

Generating the shortest paths

After the distance method, add the following:

public func shortestPath(from start: Vertex<T>) -> [Vertex<T> : Visit<T>] {
  var paths: [Vertex<T> : Visit<T>] = [start: .start] // 1

  // 2
  var priorityQueue = PriorityQueue<Vertex<T>>(sort: {
    self.distance(to: $0, with: paths) <
    self.distance(to: $1, with: paths)
  })
  priorityQueue.enqueue(start) // 3

  // to be continued
}
while let vertex = priorityQueue.dequeue() { // 1
  for edge in graph.edges(from: vertex) { // 2
    guard let weight = edge.weight else { // 3
      continue
    }
    if paths[edge.destination] == nil ||
       distance(to: vertex, with: paths) + weight <
       distance(to: edge.destination, with: paths) { // 4
      paths[edge.destination] = .edge(edge)
      priorityQueue.enqueue(edge.destination)
    }
  }
}

return paths

Finding a specific path

Add the following method to class Dijkstra:

public func shortestPath(to destination: Vertex<T>,
                         paths: [Vertex<T> : Visit<T>]) -> [Edge<T>] {
  return route(to: destination, with: paths)
}

Trying out your code

3 9 2 8 2 1 1 3 1 8 5 2 3 1 H G C E B F A D

let dijkstra = Dijkstra(graph: graph)
let pathsFromA = dijkstra.shortestPath(from: a) // 1
let path = dijkstra.shortestPath(to: d, paths: pathsFromA) // 2
for edge in path { // 3
  print("\(edge.source) --|\(edge.weight ?? 0.0)|--> \(edge.destination)")
}
D 9 9 2 0 4 0 6 5 2 1 5 1 3 0 W T O C J O D

A --|1.0|--> G
G --|3.0|--> C
C --|1.0|--> E
E --|2.0|--> D

Performance

In Dijkstra’s algorithm, you constructed your graph using an adjacency list. You used a min-priority queue to store vertices and extract the vertex with the minimum path. This process has an overall time complexity of O(log V). The heap operations of extracting the minimum element or inserting an element both take O(log V) respectively.

Key points

  • Dijkstra’s algorithm finds a path to the rest of the nodes given a starting vertex.
  • This algorithm is useful for finding the shortest paths between different endpoints.
  • Visit state is used to track the edges back to the start vertex.
  • The priority queue data structure ensures returning the vertex with the shortest path.
  • Because it chooses the shortest path at each step, it is said to be greedy!
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.
© 2025 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now