...

/

Dijkstra's Algorithm for the SSSP

Dijkstra's Algorithm for the SSSP

Learn how to solve the SSSP using Dijkstra's algorithm.

In this lesson, we’ll study Dijkstra’s algorithm, which is the most common algorithm that efficiently solves the SSSP problem.

Explanation of Dijkstra’s algorithm

Let’s use the following example graph to execute Dijkstra’s algorithm:

g a a (0) b b (?) a:e->b:nw 6 d d (?) a->d 4 c c (?) a->c 10 b:w->a:se 2 e e (?) b->e 5 b->c 3 d->b 1 d->e 2 e->c 1
An example graph for running Dijkstra's algorithm

We want to solve the SSSP problem starting from node aa, which is marked in gray, meaning that it is discovered. Like in BFS, we’ll also keep track of the distance of each node to the starting vertex. In the beginning, we’ll only know the starting vertex, and its distance is 00.

Dijkstra’s algorithm works similarly to BFS in the sense that the closest discovered, yet unexplored node is always explored first. In the beginning, we’ll need to start with node aa, the only discovered node. We’ll mark it as black, which means “finished,” and note the distances of its neighbors.

g a a (0) b b (6) a:e->b:nw 6 c c (10) a->c 10 d d (4) a->d 4 b:w->a:se 2 b->c 3 e e (?) b->e 5 d->b 1 d->e 2 e->c 1
The graph after processing node a

Here, we use the notation d(u)d(u) to refer to the distance of node uu. For example, we currently have d(b)=6d(b) = 6.

The main difference compared to regular BFS is that the distances for the discovered nodes are not yet final. They can still be improved by finding a better path. A node’s distance is only fixed once it is finished and corresponds to the length of the shortest path to the node. We now must select the closest unexplored node for exploration. Since we are now working with weighted graphs, the edge weights need to be taken into consideration when choosing the closest node. Currently, the closest node is dd, so it will be processed next. This means that we can finalize the distance of dd to be 44.

From dd, we can discover the new node ee. We’ll also find another edge to the already discovered node bb. Let’s check whether we need to update the distance of bb. The currently best-known path to bb has length 66. Our new path to node bb has a total length of 55:

  • we know that our current node dd has a distance of
...