# C++ Dijkstra Algorithm using the priority queue

In this article, we will see the implementation of the Dijkstra algorithm using the priority queue of C++ STL. Dijkstra algorithm is used to find the shortest path from the source to the destination in an undirected graph.

A graph having weight on the edges is given as below:

Let us consider a source vertex **0,** we have to find the shortest path from the source vertex to all the vertices in the graph.

Source vertex = 0

Vertex | Distance from source |
---|---|

0 | 0 Same source and destination |

1 | 4 Directly goes to 1 |

2 | 12 Path: 0 ->1 -> 2 (8 + 4 = 12) |

3 | 19 Path: 0 ->1 -> 2 -> 3 (8 + 4 + 7 = 19) |

4 | 21 Path: 0 -> 7 -> 6 -> 5 -> 4 (8 + 1 + 2 + 10 = 21) |

5 | 11 Path: 0 -> 7 -> 6 -> 5 (8 + 1 + 2 = 11) |

6 | 9 Path: 0 -> 7 -> 6 (8 + 1 = 9) |

7 | 8 Path: 0 -> 7 |

8 | 14 Path: 0 -> 1 -> 2 -> 8 (4 + 8 + 2 = 14) |

## Create graph structure

We will create a class Graph with data members as

**int v**– To store the number of vertices in the graph- List of pairs – To store the vertex and the weight associated with a particular vertex.

**list> *adj;,pair>**

**Constructors:**

We need a constructor to allocate the memory of the adjacency list.

## How to add an edge to the graph?

The list of pairs created has two arguments. One will contain the vertex, and the other will contain the weight associated with it.

As the graph is bidirectional, we can add the same weight to the opposite vertex.

**Code:**

## Algorithm

- Mark initial distance from the source is infinite.
- Create an empty priority_queue PQ. Every item of PQ is a pair (weight, vertex). Weight (or distance) is used as the first item of pair as the first item is by default used to compare two pairs.
- Insert source vertex into PQ and make its distance as 0.
- Until the priority queue defined as PQ does not become empty. Perform the operations a and b.
- Extract minimum distance vertex from PQ and let it be u.
- 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) // distance of ( v) > distance of (u) and weight from u to v- Update distance of v, i.e., do

dist[v] = dist[u] + weight(u, v) - Insert v into the pq (Even if v is

already there)

- Update distance of v, i.e., do

- Loop through the dist[] array to print the shortest paths from source to all the vertices.

## C++ code

**Output**

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