-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra_algorithm.cpp
139 lines (122 loc) · 2.09 KB
/
Dijkstra_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*
Title : Program to implement Dijkstra’s algorithm to shortest path.
*/
// Program -
#include <iostream>
using namespace std;
int visit[10];
class Graph
{
private:
int n, l, i, j, cost[10], mat[10][10], dest[10], path[20];
int edges, min, ncost, x, curdest, s, d, last, k, m;
public:
Graph()
{
edges = 1;
ncost = 0;
}
void DJ(int mat[10][10], int n);
void display();
void read();
};
void Graph::read()
{
cout << "Enter Number Vertices -->>";
cin >> n;
cout << "\nEnter The Adjacency Matrix -->>\n";
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
cin >> mat[i][j];
if (mat[i][j] == 0)
mat[i][j] = 9999;
}
}
DJ(mat, n);
}
void Graph ::DJ(int mat[10][10], int n)
{
cout << "\nEnter The Source Vertex -->> ";
cin >> s;
cout << "\nEnter the Destination Vertex -->> ";
cin >> d;
for (i = 1; i <= n; i++)
{
cost[i] = 9999;
}
cost[s] = 0;
x = s;
visit[x] = 1;
while (x != d)
{
curdest = cost[x];
min = 9999;
for (i = 1; i <= n; i++)
{
if (visit[i] == 0)
{
ncost = curdest + mat[x][i];
if (ncost < cost[i])
{
cost[i] = ncost;
dest[i] = x;
}
if (cost[i] < min)
{
min = cost[i];
k = i;
}
}
}
x = k;
visit[x] = 1;
}
display();
}
void Graph ::display()
{
l = d;
path[last] = d;
last++;
while (dest[l] != s)
{
m = dest[l];
l = m;
path[last] = l;
last++;
}
path[last] = s;
cout << "Shortest path is -->>";
for (l = last; l >= 1; l--)
{
cout << "\n"
<< path[l] << "->" << path[l - 1] << ": " << mat[path[l]][path[l - 1]];
}
cout << "\n Total Cost: " << cost[d];
}
int main()
{
Graph G;
G.read();
}
/* OUTPUT -
Enter Number Vertices -->>8
Enter The Adjacency Matrix -->>
0 1 1 1 1 0 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 0 1 0
1 0 0 0 0 0 1 0
0 1 1 0 0 0 0 1
0 0 0 1 1 0 0 1
0 0 0 0 0 1 1 0
Enter The Source Vertex -->> 1
Enter the Destination Vertex -->> 8
shortest path is
1->2: 1
2->6: 1
6->8: 1
Total Cost: 3
*/