Skip to content

Commit 94c09f1

Browse files
committed
added Dijkstra’s Algorithm
1 parent 2baeb7e commit 94c09f1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

CPP/graph_tree/Dijkstra_Algorithm.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
int main(){
4+
int n=5,m=6,source=1;
5+
vector<pair<int,int> > g[n+1]; // assuming 1 based indexing of graph
6+
// Constructing the graph
7+
g[1].push_back({2,2});
8+
g[1].push_back({4,1});
9+
g[2].push_back({1,2});
10+
g[2].push_back({5,5});
11+
g[2].push_back({3,4});
12+
g[3].push_back({2,4});
13+
g[3].push_back({4,3});
14+
g[3].push_back({5,1});
15+
g[4].push_back({1,1});
16+
g[4].push_back({3,3});
17+
g[5].push_back({2,5});
18+
g[5].push_back({3,1});
19+
// Dijkstra's algorithm begins from here
20+
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int>>> pq;
21+
vector<int> distTo(n+1,INT_MAX);//1-indexed array for calculating shortest paths
22+
distTo[source] = 0;
23+
pq.push(make_pair(0,source)); // (dist,source)
24+
while( !pq.empty() ){
25+
int dist = pq.top().first;
26+
int prev = pq.top().second;
27+
pq.pop();
28+
vector<pair<int,int> >::iterator it;
29+
for( it = g[prev].begin() ; it != g[prev].end() ; it++){
30+
int next = it->first;
31+
int nextDist = it->second;
32+
if( distTo[next] > distTo[prev] + nextDist){
33+
distTo[next] = distTo[prev] + nextDist;
34+
pq.push(make_pair(distTo[next], next));
35+
}
36+
}
37+
}
38+
cout << "The distances from source " << source << " are : \n";
39+
for(int i = 1 ; i<=n ; i++) cout << distTo[i] << " ";
40+
cout << "\n";
41+
return 0;
42+
}
43+
44+
/*
45+
Output:
46+
47+
The distances from source 1 are :
48+
0 2 4 1 5
49+
50+
Time Complexity: O((N+E)*logN). Going through N nodes and E edges and log N for priority queue
51+
52+
Space Complexity: O(N). Distance array and priority queue
53+
*/
54+
55+
////contributed by Sourav Naskar

0 commit comments

Comments
 (0)