-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra Algorithm
More file actions
49 lines (29 loc) · 1.21 KB
/
Dijkstra Algorithm
File metadata and controls
49 lines (29 loc) · 1.21 KB
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
class Solution {
public:
// Function to find the shortest distance of all the vertices
// from the source vertex src.
vector<int> dijkstra(vector<vector<pair<int, int>>> &adj, int src) {
// priotiy queue to store {dis,node}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0,src});
vector<bool> vis(adj.size(),false);
vector<int> dis(adj.size(),INT_MAX);
dis[src]=0;
while(!pq.empty()){
auto front=pq.top();
int node=front.second;
int distance=front.first;
vis[node]=true;
pq.pop();
for(auto child : adj[node]){
int cnode=child.first;
int cdis=child.second;
if(!vis[cnode] && distance + cdis < dis[cnode]){
dis[cnode] = distance + cdis;
pq.push({dis[cnode],cnode});
}
}
}
return dis;
}
};