Open In App

C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7

Last Updated : 09 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Share
8 Likes
Like
Report

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

What is Dijkstra's Algorithm?

Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate an SPT (shortest path tree) with a given source as the root. We maintain two sets, one set contains vertices included in the shortest path tree, other set includes vertices not yet included in the shortest path tree. At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a minimum distance from the source.

Below are the detailed steps used in Dijkstra's algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. 

Algorithm

  1. Create a set sptSet (shortest path tree set) that keeps track of vertices included in the shortest path tree, i.e., whose minimum distance from the source is calculated and finalized. Initially, this set is empty. 
  2. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign the distance value as 0 for the source vertex so that it is picked first. 
  3. While sptSet doesn't include all vertices 
    1. Pick a vertex u which is not there in sptSet and has minimum distance value. 
    2. Include u to sptSet
    3. Update the distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if the sum of the distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. 

C++ Program for Dijkstra's Single Source Shortest Path Algorithm


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

Complexity Analysis

Time Complexity: The time complexity of Dijkstra's algorithm is O(V^2). This is because the algorithm uses two nested loops to traverse the graph and find the shortest path from the source node to all other nodes.

Space Complexity: The space complexity of Dijkstra's algorithm is O(V), where V is the number of vertices in the graph. This is because the algorithm uses an array of size V to store the distances from the source node to all other nodes.

Please refer complete article on Dijkstra's shortest path algorithm | Greedy Algo-7 for more details!


Implementation of Dijkstra's Algorithm C++
Visit Course explore course icon
Next Article
Article Tags :
Practice Tags :

Similar Reads