forked from 20je0928/C-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra's Algo.cpp
74 lines (69 loc) · 1.57 KB
/
Dijkstra's Algo.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <climits>
#include <iostream>
using namespace std;
struct Edge {
int u;
int v;
int w;
};
struct Graph {
int V;
int E;
struct Edge* edge;
};
void dijkstra(Graph* g, int source)
{
int u, v, w;
int d[g->V];
int p[g->V];
for (int i = 0; i < g->V; i++) {
d[i] = INT_MAX;
p[i] = 0;
}
d[source] = 0;
for (int i = 0; i <= g->V - 1; i++) {
for (int j = 0; j < g->E; j++) {
u = g->edge[j].u;
v = g->edge[j].v;
w = g->edge[j].w;
if (d[u] != INT_MAX && d[v] > d[u] + w) {
d[v] = d[u] + w;
p[v] = u;
}
}
}
cout << "\nVertex\t\t:\t";
for (int i = 0; i < g->V; i++) {
cout << i << "\t";
}
cout << "\nDistance\t:\t";
for (int i = 0; i < g->V; i++) {
cout << d[i] << "\t";
}
cout << "\nParent\t\t:\t";
for (int i = 0; i < g->V; i++) {
cout << p[i] << "\t";
}
cout << endl;
}
int main()
{
Graph* g = (Graph*)malloc(sizeof(Graph));
cout << "\nEnter Number of Vertices\t:\t";
cin >> g->V;
cout << "\nEnter Number of Edges\t:\t";
cin >> g->E;
g->edge = (Edge*)malloc(g->E * sizeof(Edge));
cout << "\nEnter Edge (source , destination , weight)\n";
for (int i = 0; i < g->E; i++) {
cout << "\nEnter values for " << i + 1 << " Edge\n";
cin >> g->edge[i].u;
cin >> g->edge[i].v;
cin >> g->edge[i].w;
}
cout << "\nEnter Source Vertex\t:\t";
int s;
cin >> s;
dijkstra(g, s);
return 0;
}