forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Link State Routing
104 lines (100 loc) · 2.12 KB
/
Link State Routing
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
#include<stdio.h>
void shortest_path(int n , int cost[n][n] , int src)
{
int dist[n];
int visited[n];
int i;
int last[n];
int count;
for (i = 0; i < n ; i++)
{
dist[i] = 1000;
visited[i] = 0;
last[i] = src;
}
dist[src] = 0;
for (count = 0 ; count < n-1 ; count++)
{
int min = 1000;
int u;
for (i = 0 ; i < n ; i++)
if (visited[i] == 0 && dist[i]<= min)
{
min = dist[i];
u = i;
}
visited[u] = 1;
for (i = 0;i < n ; i++)
if (visited[i] == 0 && dist[u] + cost[u][i] < dist[i])
{
dist[i] = dist[u] + cost[u][i];
if(last[i] == src)
last[i] = u;
}
}
printf(" Routing Table of Node %d \n" , src + 1);
printf("Destination\tCost\tNext Hop \n");
for(i = 0 ; i < n ; i++)
{
if(i == src - 1)
{
printf(" %d\t\t - \t\t - \n", src + 1);
}
else
{
if(last[i] == src)
printf(" %d\t\t%d\t\t-\n", i + 1, dist[i]);
else
printf(" %d\t\t%d\t\t%d\n", i + 1, dist[i] , last[i] + 1);
}
}
printf("\n");
for(i = 0;i < n ; i++)
if(i != src)
printf(" The cost of the shortest path from router %d to %d is %d\n", src + 1 , i + 1 , dist[i]);
}
int main()
{
int n;
int i;
int j;
int src;
printf("Enter the Number of Nodes : ");
scanf("%d",&n);
int cost[n][n];
printf(" Enter the cost between Nodes : \n");
for(i = 0; i < n ; i++)
for(j = 0 ;j < n ; j++)
{
if(i != j)
{
printf("Cost from %d->%d : ",i + 1 ,j + 1);
scanf("%d",&cost[i][j]);
if(cost[i][j] == 0)
cost[i][j] = 1000;
}
else
cost[i][j] = 0;
}
printf(" Enter the source Node : ");
scanf("%d",&src);
printf("Routing Table of Node %d\n",src);
printf("Destination\tCost\tNext Hop\n");
for(i = 0; i < n ; i++)
{
if(i == src - 1)
{
printf(" %d\t\t-\t\t-\n",src);
}
else
{
if(cost[src-1][i] == 0)
printf(" %d\t\t-\t\t- \n",i+1);
else
printf(" %d\t\t%d\t\t-\n",i+1,cost[src-1][i]);
}
}
printf("After Applying Dijkstra's Algorithm\n\n");
shortest_path(n , cost , src-1);
return 0;
}