-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing.cpp
65 lines (58 loc) · 1.9 KB
/
routing.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
#include <iostream>
#include <stdio.h>
using namespace std;
struct node {
int dist[20];
int from[20];
} route[10];
int main()
{
int dm[20][20], no;
cout << "Enter no of nodes." << endl;
cin >> no;
cout << "Enter the distance matrix (enter 99 is a path doesn't exist):" << endl;
for (int i = 0; i < no; i++) {
for (int j = 0; j < no; j++) {
cout<<"Enter dist between "<<i+1<<" and "<<j+1<<": ";
cin >> dm[i][j];
/* Set distance from i to i as 0 */
dm[i][i] = 0;
route[i].dist[j] = dm[i][j];
route[i].from[j] = j;
}
}
int flag;
do {
flag = 0;
for (int i = 0; i < no; i++) {
for (int j = 0; j < no; j++) {
for (int k = 0; k < no; k++) {
if ((route[i].dist[j]) > (route[i].dist[k] + route[k].dist[j])) {
route[i].dist[j] = route[i].dist[k] + route[k].dist[j];
route[i].from[j] = k;
flag = 1;
}
}
}
}
} while (flag);
for (int i = 0; i < no; i++) {
cout << "Router info for router: " << i + 1 << endl;
cout << "Dest\tNext Hop\tDist" << endl;
for (int j = 0; j < no; j++)
printf("%d\t%d\t\t%d\n", j+1, route[i].from[j]+1, route[i].dist[j]);
}
int x,y;
cout << "Enter the nodes for which the shortest path is to be calculated:\n";
cin >> x >> y;
cout << "the path taken to travel the path is: \n";
int i=0, tx=x, ty = y;
cout << tx;
while(tx != route[tx-1].from[ty-1] + 1){
//cout << "%d %d", tx, ty);
cout << route[tx-1].from[ty-1]+1;
tx = route[tx-1].from[ty-1]+1;
}
cout << "\nthe length of the path is: " << route[x-1].dist[y-1] << endl;
return 0;
}