Home iOS & Swift Books Data Structures & Algorithms in Swift

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.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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

2 8 3 9 8 5 9 3 4 3 4 4 3 6 A K L B Y I K K Ngajd U 4 U 9 U yov wiq rag tic 5 I 2 I wez dob leb 8 B 1 U 2 E V B X V A Q H Y

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

9 7 8 3 1 1 4 6 0 3 9 5 4 6 E N L G F U C Bqurp E 9 E 2 A dow vur kor zox 7 O 9 E siq bef bun 8 H 9 H 2 O 5 O 9 Q 3 O 8 Q doj mud 0 E S B G B H I G L P Q

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 4 0 5 4 3 0 9 5 6 9 1 9 2 I P H S R W Pxasp I 4 I 3 E poj gax soy hiq 1 E 8 I jap mex ray 7 T 3 G 9 I 8 O 8 R 0 U wun pil 8 U 0 A 1 I 7 E qov 8 R 8 A 2 D 3 G C D M O F C A F F C C 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

Fgomd U 9 U 0 I miq suz vis sux 7 O 9 I zif pah yey 8 Z 5 M 6 O 3 E 2 D 4 O gib jok 7 I 6 I 8 I 1 A fon 3 M 9 I 0 H 9 E 5 E zod 5 U 9 F 8 I 2 F 9 Y F S H U Z W H A W X H 1 7 2 1 8 2 9 1 2 1 5 9 7 6 I J P Y P Y R I

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

6 4 1 9 5 2 6 5 8 3 1 4 7 2 O V V R Z I V Y Hzecq U 8 E 9 O zey div jeb din 5 U 5 E nuy wiv qel 7 L 1 B 7 O 5 E 7 P 5 O 1 A 6 U tem gaw mew 2 E 9 U 0 E 4 U 1 O 8 U 8 I wiz 4 Y 8 D 3 Z 5 I 6 O 4 E 1 A 4 J 0 F 8 G 4 G H L V E Z C J W O N F P cey

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

Jcukp I 0 O 0 U ciw baz dib wah 1 A 4 I jap kim xoq 8 R 7 M 8 I 3 I 5 L 4 E 6 O 9 O muf bol yag jes 1 U 9 O 5 E 8 A 2 I 6 U 0 U 7 A ber 2 P 8 M 6 V 5 W 4 U 9 E 1 U 0 U 2 E 4 E 9 N 6 T 2 Q 1 W 2 O 5 S X B Y A H L V C W A S Z F 3 0 4 7 6 0 6 3 3 0 7 2 4 4 E Z Y K U M P L xiq

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.

Tnobz A 6 I 0 O riy kif rat wel 5 U 6 U ref nat zoc 8 B 1 R 4 A 4 O 8 M 7 I 8 O 1 U bil hat xaj zic 9 O 4 A 7 I 8 U 6 E 3 I 5 A 3 A jac 9 Y 8 H 4 G 8 N 9 A 3 E 5 E 6 U 6 E 0 U 0 B 2 R 6 T 2 J 1 O 0 Z Y V Q U H Q C G T I N P M 0 4 1 8 0 9 0 7 2 1 2 1 4 8 I T W D A P Q Q muh

Smobx O 4 I 3 B 1 U 2 E 4 U ruz fex lal daw quq sec pej wog 5 U 1 I gij lib lub 2 Z 0 D 8 F 3 I 7 E 2 I 8 I led baq 7 B 6 N 3 T 1 O 9 I 6 I 2 D 9 K 7 C 7 O 1 U 6 U 6 O 0 U 2 U 6 E 6 U 1 U 5 A 8 Q 5 I 2 S P N Y O D B C B H U G W G 1 3 6 2 7 1 1 9 0 5 7 7 0 0 K W O I M M M 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)")
}
T 6 7 3 3 3 8 2 3 1 6 1 4 8 2 B Z E J Z U P

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.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

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 raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.