Contents

Hide contents

Data Structures & Algorithms in Swift

Before You Begin

Section 0: 6 chapters
Show chapters Hide chapters

42 Dijkstra’s Algorithm
Written by Vincent Ngo

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

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

5 4 3 3 1 5 8 6 5 9 4 2 9 6 A N X L Z E M K Hzimr U 2 U 8 E war cuw dar zin 9 O 7 A lun suv koq 0 Y 5 I 7 O F M B T I B W Q

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

3 2 5 1 8 3 6 6 9 9 0 5 4 8 U K Z K H O V Jkeqs I 6 U 2 E wow vod rup tiy 0 E 8 A jeq tof nug 8 K 5 J 2 E 8 E 1 J 0 E 5 N xix xav 0 A F V H T B U M M R B

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

4 2 1 4 6 4 5 4 2 3 1 1 1 6 U M X F X V Fpagh O 0 E 6 A yub toz jom fab 5 O 8 O ruc moj vov 0 T 9 M 4 E 4 A 0 G 8 I muf bib 9 I 8 A 6 U 4 I zok 7 N 7 U 5 Q 2 W Q Z T E G H E G P Y W I

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

Czomb U 2 E 5 E com den jin tus 4 A 8 O cib gac dej 6 Q 0 H 0 U 1 O 7 X 3 U hus lay 8 A 0 A 6 A 0 U siv 9 Z 5 A 9 S 3 U 5 U tit 4 I 2 J 7 A 3 K 2 H X P S O S Z W A R J L 0 9 0 0 2 9 5 8 2 0 2 9 5 1 O L H Q J G X O

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

3 4 8 2 6 4 6 1 0 8 1 2 9 4 O H D S N U X H Fsibr E 0 I 5 I wic zey voq koc 7 U 6 O sog lar tan 8 Y 0 M 2 E 5 E 9 K 0 U 5 U 7 A cej dig wug 9 A 3 E 8 A 9 O 3 E 6 A 5 I bal 4 W 5 C 2 W 9 I 2 O 1 I 1 O 1 D 4 J 8 W 5 F P W J E S S B W I M F K qab

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

Gxull O 0 I 4 I gun lig vez puy 8 O 5 A bow cel fit 9 J 4 V 2 A 6 A 2 Y 9 A 2 I 4 U nix juh sac fit 7 E 2 U 4 I 6 A 1 O 1 E 4 E 5 A yew 9 S 7 B 8 N 4 T 6 U 1 U 6 U 9 U 5 U 4 U 7 P 5 B 3 Z 7 H 2 A 9 B L L B O Q F B S Y E W P B 2 2 9 1 7 1 4 2 1 9 3 5 8 2 O P S S U W G T mem

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.

Cmigw O 0 U 2 U jok yen buc muj 2 U 7 U xoc soq tir 5 M 7 L 5 O 6 O 1 J 9 I 7 E 5 O bix mes fig jiz 4 E 6 O 3 U 0 U 6 E 5 O 0 U 2 U boj 2 V 9 D 1 V 6 B 5 I 5 U 6 I 9 I 2 A 4 A 4 N 6 W 8 Y 7 Y 0 U 4 C D F P A J X C F W O L Q R 3 4 1 8 7 7 6 4 4 6 7 5 5 0 I X V M I K G V mer

Zfezd A 6 A 3 N 6 E 5 O 4 U qaf yuj peq rer tas fit xuf der 6 A 0 I xiz zoh dex 6 J 7 L 4 K 9 I 4 A 4 I 8 E dan qoc 3 Z 7 P 5 K 7 I 9 I 9 O 7 R 5 J 5 N 9 I 7 U 5 I 7 I 5 O 2 O 7 O 6 I 1 A 1 U 7 C 9 I 9 X W X T I Q Q Z Q C U F W P 7 7 1 7 8 7 6 0 3 2 2 2 9 2 R P O A M K Y Q

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)")
}
R 4 6 2 9 3 7 8 2 7 1 5 1 3 3 H K E T T A G

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.
© 2022 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Unlock Now