Now obtain Routing table for each node using distance vector routing algorithm Algorithm:
Input: Graph and a given vertex src
Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.
1) This step initializes distances from source to all vertices as infinite and distance to source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.
2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph.
…..a) Do following for each edge v-u
………………If dist[v] > dist[u] + weight of edge uv, then update dist[v]
………………….dist[v] = dist[u] + weight of edge uv
3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-v
……If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle” The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle
Program:
#include<stdio.h>
#include<math.h>
#include<conio.h>
main()
{
int i,j,k,nv,sn,noadj,edel[20],tdel[20][20],min; char sv,adver[20],ch;
clrscr();
printf("\n ENTER THE NO.OF VERTECES:");
scanf("%d",&nv);
printf("\n ENTER THE SOURCE VERTEX NUM,BER AND NAME:");
scanf("%d",&sn);
flushall(); sv=getchar();
printf("\n NETER NO.OF ADJ VERTECES TO VERTEX %c",sv);
scanf("%d",&noadj);
for(i=0;i<noadj;i++)
{
printf("\n ENTER TIME DELAY and NODE NAME:");
scanf("%d %c",&edel[i],&adver[i]);
}
for(i=0;i<noadj;i++)
{
printf("\n ENTER THE TIME DELAY FROM %c to ALL OTHER
NODES: ",adver[i]); for(j=0;j<nv;j++)
scanf("%d",&tdel[i][j]);
}
printf("\n DELAY VIA--VERTEX \n ");
for(i=0;i<nv;i++)
{
min=1000; ch=0; for(j=0;j<noadj;j++)
if(min>(tdel[j][i]+edel[j]))
{
min=tdel[j][i]+edel[j]; ch=adver[j];
}
if(i!=sn-1)
printf("\n%d %c",min,ch);
else
printf("\n0 -");
}
getch();
}
INPUT/OUTPUT:
ENTER THE NO.OF VERTECES:12
ENTER THE SOURCE VERTEX NUMBER AND NAME:10 J
ENTER NO.OF ADJ VERTECES TO VERTEX 4 ENTER TIME DELAY and NODE NAME:8 A ENTER TIME DELAY and NODE NAME:10 I ENTER TIME DELAY and NODE NAME:12 H ENTER TIME DELAY and NODE NAME:6 K
ENTER THE TIME DELAY FROM A to ALL OTHER NODES: 0 12 25 40 14 23 18 17 21 9 24 29
ENTER THE TIME DELAY FROM I to ALL OTHER NODES: 24 36 18 27 7 20 31 20 0 11 22 33
ENTER THE TIME DELAY FROM H to ALL OTHER NODES: 20 31 19 8 30 19 6 0 14 7 22 9
ENTER THE TIME DELAY FROM K to ALL OTHER NODES: 21 28 36 24 22 40 31 19 22 10 0 9
DELAY VIA--VERTEX
8 a
20 a
28 i
20 h
17 i
30 i
18 h
12 h
10 i
0 -
6 k 15 k