-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra_code.cpp
More file actions
67 lines (52 loc) · 1.4 KB
/
Copy pathDijkstra_code.cpp
File metadata and controls
67 lines (52 loc) · 1.4 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
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e7;
int main()
{
int n, m;
cout << "Enter number of Vertex: ";
cin >> n;
cout << "\nEnter number of Edges: ";
cin >> m;
vector<int> distance(n + 1, inf);
vector<vector<pair<int, int>>> graph(n + 1);
cout << "\nEnter all the nodes and weight between two nodes: format(u, v, w)" << endl;
for (int i = 0; i < m; i++)
{
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
graph[v].push_back({u, w});
}
int source;
cout << "\nEnter the source node: ";
cin >> source;
distance[source] = 0;
set<pair<int, int>> s;
s.insert({0, source});
while (!s.empty())
{
auto x = *(s.begin());
s.erase(x);
for (auto it : graph[x.second])
{
if (distance[it.first] > distance[x.second] + it.second)
{
s.erase({distance[it.first], it.first});
distance[it.first] = distance[x.second] + it.second;
s.insert({distance[it.first], it.first});
}
}
}
for (int i = 1; i <= n; i++)
{
if (distance[i] < inf)
{
cout << "Shortest Distance from node " << source << " to destination node " << i << " : " << distance[i] << endl;
}
else
{
cout << -1 << " ";
}
}
}