forked from strivedi4u/hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijkastra Algorithm.cpp
60 lines (47 loc) · 1.27 KB
/
Dijkastra Algorithm.cpp
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
60
#include<bits/stdc++.h>
using namespace std;
vector<int> dijkstra(int V, vector<vector<int>> adj[], int S) {
vector<vector<int>> graph(V, vector<int>(V, 0));
for (int i = 0; i < V; i++) {
for (auto &vec : adj[i]) {
int v = vec[0];
int w = vec[1];
graph[i][v] = w;
}
}
vector<int> vis(V, 0);
vector<int> dist(V, INT_MAX);
dist[S] = 0;
for (int count = 0; count < V; count++) {
int u = -1;
for (int i = 0; i < V; i++) {
if (!vis[i] && (u == -1 || dist[u] > dist[i])) {
u = i;
}
}
vis[u] = 1;
for (int v = 0; v < V; v++) {
if (!vis[v] && graph[u][v] != 0) {
dist[v] = min(dist[v], dist[u] + graph[u][v]);
}
}
}
return dist;
}
int main() {
int V, E, S;
cin >> V >> E;
vector<vector<int>> adj[V];
for (int i = 0; i < E; i++) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
cin >> S;
vector<int> result = dijkstra(V, adj, S);
for (int i = 0; i < V; i++) {
cout << result[i] << " ";
}
return 0;
}