Dijkstra’s Shortest Path Algorithm using priority_queue of STL

• Difficulty Level : Medium
• Last Updated : 16 Jul, 2022

Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph.

Input : Source = 0
Output :
Vertex   Distance from Source
0                0
1                4
2                12
3                19
4                21
5                11
6                9
7                8
8                14

We have discussed Dijkstra’s shortest Path implementations.

The second implementation is time complexity wise better but is really complex as we have implemented our own priority queue. The Third implementation is simpler as it uses STL. The issue with third implementation is, it uses set which in turn uses Self-Balancing Binary Search Trees. For Dijkstra’s algorithm, it is always recommended to use heap (or priority queue) as the required operations (extract minimum and decrease key) match with speciality of heap (or priority queue). However, the problem is, priority_queue doesn’t support decrease key. To resolve this problem, do not update a key, but insert one more copy of it. So we allow multiple instances of same vertex in priority queue. This approach doesn’t require decrease key operation and has below important properties.

• Whenever distance of a vertex is reduced, we add one more instance of vertex in priority_queue. Even if there are multiple instances, we only consider the instance with minimum distance and ignore other instances.
• The time complexity remains O(ELogV)) as there will be at most O(E) vertices in priority queue and O(Log E) is same as O(Log V)

Below is algorithm based on above idea.

1) Initialize distances of all vertices as infinite.

2) Create an empty priority_queue pq.  Every item
of pq is a pair (weight, vertex). Weight (or
distance) is used  as first item  of pair
as first item is by default used to compare
two pairs

3) Insert source vertex into pq and make its
distance as 0.

4) While either pq doesn't become empty
a) Extract minimum distance vertex from pq.
Let the extracted vertex be u.
b) Loop through all adjacent of u and do
following for every vertex v.

// If there is a shorter path to v
// through u.
If dist[v] > dist[u] + weight(u, v)

(i) Update distance of v, i.e., do
dist[v] = dist[u] + weight(u, v)
(ii) Insert v into the pq (Even if v is

5) Print distance array dist[] to print all shortest
paths.

Below is C++ implementation of above idea.

CPP

Output

Vertex Distance from Source
0          0
1          4
2          12
3          19
4          21
5          11
6          9
7          8
8          14

A Quicker Implementation using vector of pairs representation of weighted graph

CPP

Output

Vertex Distance from Source
0          0
1          4
2          12
3          19
4          21
5          11
6          9
7          8
8          14