-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImplementing Dijkstra's Algorithm
58 lines (52 loc) · 1.94 KB
/
Implementing Dijkstra's Algorithm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution
{
public:
//Function to find the shortest distance of all the vertices
//from the source vertex S.
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
//using priority Queue:
// priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// vector<int> dist(V, 1e9);
// dist[S] = 0;
// pq.push({0, S});
// while(!pq.empty()){
// int dis = pq.top().first;
// int node = pq.top().second;
// pq.pop();
// for(auto it: adj[node]){
// int edgeWeight = it[1];
// int adjNode = it[0];
// if(dis + edgeWeight < dist[adjNode]){
// dist[adjNode] = dis + edgeWeight;
// pq.push({dist[adjNode], adjNode});
// }
// }
// }
// return dist;
//Using Set
set<pair<int, int>> st;
vector<int> dist(V, 1e9);
st.insert({0, S});
dist[S] = 0;
while(!st.empty()){
auto it = *(st.begin());
int dis = it.first;
int node = it.second;
st.erase(it);
for(auto it: adj[node]){
int edgeWeight = it[1];
int adjNode = it[0];
if(dis + edgeWeight < dist[adjNode]){
//check if that node is visited or not i.e the dist is 1e9 or not
//if dist is not 1e9 and we have better dist than previous then erase that node
//from set and add new node with better dist than previous it can save time
if(dist[adjNode] != 1e9) st.erase({dist[adjNode], adjNode});
dist[adjNode] = dis + edgeWeight;
st.insert({dist[adjNode], adjNode});
}
}
}
return dist;
}
};