...

/

Dijkstra’s Algorithm

Dijkstra’s Algorithm

Learn how Dijkstra’s algorithm works.

In this lesson, we look at another algorithm for solving the single-source shortest-paths problem called Dijkstra’s algorithm. Dijkstra’s algorithm is the preferred algorithm for finding the shortest paths from a single source because it also works for digraphs that have cycles. However, it does fail to work for digraphs with negative edge weights. The principal idea behind Dijkstra’s algorithm appears, in its rudimentary form, in a 1959 paper"A note on two problems in connexion with graphs", Numerische Mathematik 1, 269 – 271 by the famous Dutch computer scientist Edsger Dijkstra.

Main idea

Given a weighted digraph GG, the algorithm works so that throughout its execution, vertices of GG remain conceptually partitioned into two sets MM and its complement MC=VMM^C = V−M, as shown in the following figure.

Press + to interact
Graph vertices partitioned into sets M and its complement
Graph vertices partitioned into sets M and its complement

Initially, the set MM is empty so that all vertices of GG are in its complement MCM^C. In each round, we repeat the following steps:

  1. We pick a vertex vv in MCM^C with the smallest v.distv.dist value (amongst all vertices in MCM^C) and add it to MM.

    Note: The first vertex added to M is the source vertex since it’s the only vertex whose distdist attribute is initialized to 00 instead of \infty.

  2. With each vertex added to MM, we perform an edge-relaxation for all the edges originating at that vertex.

Once all vertices are added to the set MM, we consider the lengths of the shortest paths and the parent pointers correctly computed in the v.distv.dist and v.parentv.parent attributes for each vertex vv.

Visualization

We give a simulation of how Dijkstra’s algorithm would work on a digraph. In the following slides, attributes of each vertex added to MM in a round are shown in blue boxes. Attributes of vertices present in MCM^C are shown in grey boxes.

Press + to interact
A weighted digraph
1 / 15
A weighted digraph

Choice of data structure

To implement the above description, we can keep the vertices of ...