Skip to content

Commit e11b2d6

Browse files
committed
Added Dijkstra's Algorithm in cpp
1 parent 5309c78 commit e11b2d6

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/* A C++ program for Dijkstra's algorithm. The program Used
2+
the adjacency matrix
3+
Ask the input from the user the num of edges,
4+
num of vertices and the graph with the value of each edge
5+
It will print the minimum cost from source to destination
6+
7+
Nodes should be provided from the index 1
8+
9+
*/
10+
#include <bits/stdc++.h>
11+
using namespace std;
12+
struct compare{
13+
bool operator()(pair<int, int>&a, pair<int, int>&b){
14+
return a.first > b.first;
15+
}
16+
};
17+
18+
int findMinPath(vector<vector<int>>& graph, int n, int src, int dest){
19+
vector<int>distance(n, INT_MAX);//it will the shortest distance from source to every node
20+
21+
vector<bool>visited(n, false);
22+
23+
distance[src] = 0;
24+
25+
priority_queue<pair<int, int>, vector<pair<int, int>>, compare>qt;
26+
27+
int connect = 0;
28+
29+
int i = src;
30+
int total = 0;
31+
32+
//loop will work untill reach the destination
33+
while( i != dest ){
34+
35+
visited[i] = true;
36+
37+
int j = 0;
38+
39+
while(j < n){
40+
if (!visited[j] && graph[i][j]!=-1 && distance[i]!=INT_MAX && distance[i] + graph[i][j] < distance[j]){
41+
distance[j] = distance[i] + graph[i][j];
42+
qt.push(make_pair(distance[j], j));
43+
}
44+
j++;
45+
}
46+
47+
//pop the mini value from the priority queue
48+
int dis = qt.top().first;
49+
cout << dis << "\n";
50+
51+
total = dis;
52+
53+
i = qt.top().second;
54+
qt.pop();
55+
}
56+
return total;
57+
58+
}
59+
int main(){
60+
int num_vertices;
61+
cin >> num_vertices;
62+
63+
int num_edges;
64+
cin >> num_edges;
65+
vector<vector<int>>graph(num_vertices, vector<int>(num_vertices, -1));
66+
67+
int a, b, val;
68+
for(int i=0;i<num_edges;i++){
69+
cin >> a;
70+
cin >> b;
71+
cin >> val;
72+
graph[a-1][b-1] = val;
73+
graph[b-1][a-1] = val;
74+
}
75+
int source_vertex;
76+
cin >> source_vertex;
77+
78+
int dest_vertex;
79+
cin >> dest_vertex;
80+
81+
82+
int min_cost = findMinPath(graph, num_vertices, source_vertex-1, dest_vertex-1);
83+
84+
cout << "Minimum cost of total Path " << min_cost <<"\n";
85+
86+
return 0;
87+
}

0 commit comments

Comments
 (0)