0% found this document useful (0 votes)
3 views3 pages

Dijkstra's Algorithm Implementation in C++

The document contains a C++ program that implements Dijkstra's algorithm using a greedy method to find the shortest paths from a source vertex in a directed graph. It includes a class definition for the graph, methods to prepare the adjacency list, and to compute distances using Dijkstra's algorithm. The program prompts the user for the number of vertices and edges, and outputs the shortest distances from the source vertex to all other vertices.

Uploaded by

gauravbajaj2706
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Dijkstra's Algorithm Implementation in C++

The document contains a C++ program that implements Dijkstra's algorithm using a greedy method to find the shortest paths from a source vertex in a directed graph. It includes a class definition for the graph, methods to prepare the adjacency list, and to compute distances using Dijkstra's algorithm. The program prompts the user for the number of vertices and edges, and outputs the shortest distances from the source vertex to all other vertices.

Uploaded by

gauravbajaj2706
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAM-5

Aim:- Program to implement Dijkstra’s algorithm using greedy method.


Source Code:-
#include<bits/stdc++.h>
using namespace std;
class graph{
public:
unordered_map<char,vector<pair<char,int>>>adjList;
vector<pair<pair<char,char>,int>>edges;
vector<char>vertices;
void prepareAdjList(){
for(int i=0;i<[Link]();i++){
char u=edges[i].[Link];
char v=edges[i].[Link];
int w=edges[i].second;
adjList[u].push_back({v,w});
}
}
vector<int>dijkstra(int n,int source){
vector<int>dist(n,INT_MAX);
set<pair<int,int>>st;
dist[source]=0;
[Link]({0,source});
while(![Link]()){
auto top=*([Link]());
int nodeDistance=[Link];
int topNode=[Link];
[Link]([Link]());
for(auto neighbour:adjList[vertices[topNode]]){
if((nodeDistance+[Link])<dist[[Link]-vertices[0]]){
auto record=[Link]({dist[[Link]-vertices[0]],[Link]-
vertices[0]});
if(record!=[Link]()){
[Link](record);
}
dist[[Link]-vertices[0]]=nodeDistance+[Link];
[Link]({dist[[Link]-vertices[0]],[Link]-vertices[0]});
}
}
}
return dist;
}
};
int main(){
graph g;
int n;
cout<<"Enter no. of vertices: ";
cin>>n;
cout<<"Enter all vertices of directed graph(in lexicographically order): ";
for(int i=0;i<n;i++){
char v;
cin>>v;
[Link].push_back(v);
}
int m;
cout<<"Enter no. of edges: ";
cin>>m;
cout<<"Enter all edge pairof Directed graph with their weight: "<<endl;
for(int i=0;i<m;i++){
cout<<"Enter edge pair with weight: ";
char u,v;
int w;
cin>>u>>v>>w;
pair<pair<int,int>,int>p={{u,v},w};
[Link].push_back(p);
}
[Link]();
cout<<"Taking '"<<[Link][0]<<"' as a source node for Dijkstra algorithm"<<endl;
vector<int>res=[Link](n,0);
cout<<"Shortest distance of every vertices taking '"<<[Link][0]<<"' as a source
node:"<<endl;
for(int i=0;i<[Link]();i++){
cout<<[Link][0]<<"->"<<[Link][i]<<": "<<res[i]<<endl;
}
return 0;
}

OUTPUT:-

Common questions

Powered by AI

The first vertex is taken as the source node to provide a starting point for the Dijkstra algorithm, ensuring consistent comparison of distances from a fixed origin. This choice simplifies input handling and output generation, allowing the programmer to set a specific point from which all shortest paths are determined. It reflects a convention that aligns with the function's requirement to have a single source node to compute shortest paths to all other vertices in the graph .

The program ensures correctness by initially setting the source vertex distance to zero and all other vertices to infinity. It utilizes a greedy approach, selecting the vertex with the minimum current distance from the set, and updates the distances to its neighbors if a shorter path is found through the current vertex. By dynamically adjusting distances and maintaining an ordered set of vertices, the algorithm efficiently computes the shortest paths, ensuring each vertex’s distance reflects the minimum possible value by the time it is removed from the set .

Erasing and updating vertices within the set is essential to ensure that the vertex distances accurately reflect the shortest paths as they are dynamically calculated. By removing and reinserting vertices with updated distances, the set maintains its property of being ordered by distance, allowing efficient retrieval of the vertex with the minimum current distance. This operation is vital to optimizing the algorithm's runtime by ensuring that outdated paths are not considered, thus maintaining the integrity of the shortest path computation .

Vertices are specified in lexicographical order to maintain a consistent and predictable order of traversal and output, ensuring that the algorithm operates correctly when mapping character vertices to array indices. This explicit ordering simplifies the management of vertex indices and enhances readability and correctness in determining shortest paths and distances when presenting output. It is crucial for ensuring that the operations relying on character-to-index mapping operate correctly throughout the algorithm .

The program uses an adjacency list to represent the graph, implemented through an unordered_map where each vertex is associated with a vector of pairs, each pair containing a neighboring vertex and the weight of the edge connecting them. During execution, it creates a set to efficiently manage the vertices currently under exploration, updating distances while ensuring lexicographical ordering of vertices is maintained. The adjacency list is prepared by iterating over all edges, converting the edge list representation into adjacency list format, which facilitates fast access to a vertex's neighbors during the Dijkstra algorithm's execution .

Edge weights are incorporated into the adjacency list as part of a pair, where each pair consists of a neighboring vertex and the associated edge weight. This setup allows the algorithm to accurately compute the sum of path weights, facilitating the updating of tentative distances within the Dijkstra algorithm. By ensuring each adjacent vertex is paired with its edge weight, the adjacency list supports prompt access and update operations required when relaxing edges during the step-by-step exploration of vertices. This approach enables the algorithm to efficiently find shortest paths by systematically minimizing cumulative path weights .

Potential inefficiencies include the use of a set for managing vertices, which, while effective in maintaining an order, can be less performant than a priority queue (using a binary heap), especially during update operations. Additionally, modifying the set can lead to increased overhead. These inefficiencies can be mitigated by using a priority queue data structure like a binary heap or Fibonacci heap to more efficiently perform the necessary operations on vertex distances, reducing the time complexity from O(n log n) (with a set) to potentially O(log n) operations per vertex .

The primary purpose of using a set in the implementation is to efficiently manage and retrieve the vertex with the current smallest tentative distance in the graph. A set provides automatic ordering and allows quick access to the element with the minimum distance, facilitating the greedy step of Dijkstra's algorithm where the closest vertex is selected to update neighboring distances. This improves the efficiency of the algorithm compared to using a simple array or list .

Not preparing the adjacency list correctly would significantly impede the execution of Dijkstra's algorithm by causing incorrect neighbor lookups and path calculations. An improperly constructed adjacency list can lead to invalid distance updates, missed vertices, or unaccounted edges in the shortest path computation. It undermines the algorithm's foundational logic, resulting in flawed or incomplete path outputs that cannot be reliably verified. Proper adjacency list preparation ensures accurate and efficient access to vertex neighbors, directly impacting the algorithm's ability to consistently determine shortest paths .

The program outputs the shortest paths explicitly to provide a clear and verifiable result of the algorithm's execution. By demonstrating the computed shortest paths and distances, it enables users to easily validate the correctness and functionality of the implementation by comparing the output against expected values for known test cases. Explicit output serves as a form of verification, helping assure that the algorithm is functioning as intended by providing tangible evidence of its computational process .

You might also like