-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDijkstra.cpp
More file actions
79 lines (74 loc) · 1.66 KB
/
Dijkstra.cpp
File metadata and controls
79 lines (74 loc) · 1.66 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
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<climits>
#define pp pair<int,int>
using namespace std;
int dis[100];
int parent[100];
struct node
{
bool operator()(const pair<int,int>&p1, const pair<int,int>&p2)
{
return p1.second < p2.second;
}
};
vector<pp> adj[100];
void printPath(int parent[],int j)
{
if(parent[j] == -1)
return;
printPath(parent,parent[j]);
cout<<j<<"->";
}
void dijkstra(int n,int source)
{
int u,v,w,i;
priority_queue<pp, vector<pp>,node> pq;
memset(dis,100,sizeof(dis));
memset(parent,-1,sizeof(parent));
dis[source] = 0;
pq.push(pp(source,dis[source]));
while(!pq.empty())
{
u = pq.top().first;
pq.pop();
for(i=0;i<adj[u].size();i++)
{
v = adj[u][i].first;
w = adj[u][i].second;
if(dis[v] > dis[u]+w)
{
dis[v] = dis[u]+w;
pq.push(pp(v,dis[v]));
parent[v]=u;
}
}
}
for(i=1;i<=n;i++)
{
cout<<"Vertex "<<i<<" "<<"Minimum distance = "<<dis[i]<<" path "<<source<<"->";
printPath(parent,i);
cout<<endl;
}
return;
}
int main()
{
int n,e,source,i;
int u,v,w;
cout<<"Enter number of nodes and edges: "<<endl;
cin>>n>>e;
cout<<"vertex to vertex and its weight: \n";
while(e--)
{
cin>>u>>v>>w;
adj[u].push_back(pp(v,w));
adj[v].push_back(pp(u,w));
}
cout<<"Enter the starting node: ";
cin>>source;
dijkstra(n,source);
return 0;
}