Implementation of Dijkstra

Implementation notes

As we saw in the previous lesson, Dijkstra’s algorithm is very similar to BFS in the sense that the closest unexplored node is processed next within the order of processing. However, determining the closest node needs to consider the distance estimates known so far, and that they can change over time. Therefore, it is not possible to simply store the unfinished nodes in a static queue data structure.

A naive implementation could simply store the currently known distance of each node in a vector and check all the unexplored nodes during each iteration to get the node with the minimum distance. However, this would lead to a time complexity of O(V2)\mathcal{O}(|V|^2), and we can do better.

Instead, we should use a data structure that allows us to efficiently get the node with the lowest distance estimate. Additionally, the data structure should support updating the distance estimate of a vertex. Both properties can be fulfilled by using a priority queue data structure to store the nodes and their distances.

The following illustration shows how such a priority queue looks during the execution of Dijkstra’s algorithm:

Get hands-on with 1200+ tech skills courses.