C++ Dijkstra Algorithm using the priority queueIn 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
Create graph structureWe will create a class Graph with data members as
list 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
C++ codeOutput Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 Next TopicConstructor overloading in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India