Chapter 42: Dijkstra’s Algorithm

前言

  • 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.

大綱

  • Example

  • Implementation

    • Helper methods

      • Tracing back to the start

      • Calculating total distance

    • Generating the shortest paths

    • Finding a specific path

  • Trying out your code

  • Performance

Example

  • Every value in the output table has two parts:

    • the total cost to reach that vertex

    • the last neighbor on the path to that vertex.

    • For example, the value 4 G in the column for vertex C means that the cost to reach C is 4

Init

Tracing back to the start

Calculating total distance

Generating the shortest paths

Finding a specific path

Performance

  • Constructed your graph using an adjacency list

  • Used a min-priority queue to store vertices and extract the vertex with the minimum path.

    • heap operations of extracting the minimum element or inserting an element both take O(log V)

  • Dijkstra’s algorithm is somewhat similar to breadth-first search

    • O(V + E) to traverse all the vertices and edges

    • use a min-priority queue to select a single vertex with the shortest distance to traverse down. That means it is O(1 + E) or simply O(E)

  • it takes O(E log V) to perform Dijkstra’s algorithm

Last updated