-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathDijkstra's Algorithm
More file actions
59 lines (43 loc) · 1.29 KB
/
Copy pathDijkstra's Algorithm
File metadata and controls
59 lines (43 loc) · 1.29 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
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii; // (distance, node)
void dijkstra(int source, vector<vector<pii>>& graph, int V) {
vector<int> dist(V, INT_MAX);
dist[source] = 0;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, source});
while (!pq.empty()) {
int currentDist = pq.top().first;
int u = pq.top().second;
pq.pop();
if (currentDist > dist[u]) continue;
for (auto& edge : graph[u]) {
int v = edge.first;
int weight = edge.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
cout << "Shortest distances from source " << source << ":\n";
for (int i = 0; i < V; i++) {
if (dist[i] == INT_MAX)
cout << i << " : INF\n";
else
cout << i << " : " << dist[i] << "\n";
}
}
int main() {
int V = 5;
vector<vector<pii>> graph(V);
graph[0].push_back({1, 4});
graph[0].push_back({2, 8});
graph[1].push_back({2, 3});
graph[1].push_back({4, 6});
graph[2].push_back({3, 2});
graph[3].push_back({4, 10});
int source = 0;
dijkstra(source, graph, V);
return 0;
}