-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.cpp
More file actions
98 lines (79 loc) · 1.35 KB
/
Copy pathalgorithm.cpp
File metadata and controls
98 lines (79 loc) · 1.35 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include<iostream>
using namespace std;
#define INF 999
int U, src, cost[100][100];
int dist[100];
bool visited[100] = { 0 };
int Prnt[100];
void init()
{
for (int x = 0; x < U; x++)
{
Prnt[x] = x;
dist[x] = INF;
}
dist[src] = 0;
}
int getNearest()
{
int minimumValue = INF;
int minimumNode = 0;
for (int x = 0; x < U; x++)
{
if (!visited[x] && dist[x] < minimumValue)
{
minimumValue = dist[x];
minimumNode = x;
}
}
return minimumNode;
}
void djkAlgorithm()
{
for (int x = 0; x < U; x++)
{
int nearest = getNearest();
visited[nearest] = true;
for (int adj = 0; adj < U; adj++)
{
if (cost[nearest][adj] != INF &&
dist[adj] > dist[nearest] + cost[nearest][adj])
{
dist[adj] = dist[nearest] + cost[nearest][adj];
Prnt[adj] = nearest;
}
}
}
}
void display()
{
cout << "Node:\t\t\tCost :\t\t\tPath";
for (int x = 0; x < U; x++)
{
cout << x << "\t\t\t" << dist[x] << "\t\t\t" << " ";
cout << x << " ";
int parnode = Prnt[x];
while (parnode != src)
{
cout << " <-- " << parnode << " ";
parnode = Prnt[parnode];
}
cout << endl;
}
}
int main(void) {
cout << "Enter the number of vertives : ";
cin >> U;
for (int x = 0; x < U; x++)
{
for (int y = 0; y< U; y++)
{
cin >> cost[x][y];
}
}
cout << "Enter Src Node : ";
cin >> src;
init();
djkAlgorithm();
display();
}