Skip to content

Commit 1f1deb3

Browse files
Add link state routing protocol
1 parent e1f2a40 commit 1f1deb3

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

linkstatera.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include<stdio.h>
2+
#include<iostream>
3+
#define INFINITY 9999
4+
#define MAX 10
5+
using namespace std ;
6+
void dijkstra(int G[MAX][MAX],int n,int startnode) ;
7+
int main()
8+
{
9+
int G[MAX][MAX],i,j,n,u ;
10+
cout<<"Enter number of nodes : " ;
11+
cin>>n ;
12+
cout<<"\nEnter the distance matrix : \n" ;
13+
for(i=0 ; i<n ; i++)
14+
for(j=0 ; j<n ; j++)
15+
cin>>G[i][j] ;
16+
cout<<"\nEnter the starting node : " ;
17+
cin>>u ;
18+
dijkstra(G,n,u) ;
19+
return 0 ;
20+
}
21+
void dijkstra(int G[MAX][MAX],int n,int startnode)
22+
{
23+
int cost[MAX][MAX],distance[MAX],pred[MAX] ;
24+
int visited[MAX],count,mindistance,nextnode,i,j ;
25+
for(i=0 ; i<n ; i++)
26+
for(j=0 ; j<n ; j++)
27+
if(G[i][j]==0)
28+
cost[i][j] = INFINITY ;
29+
else
30+
cost[i][j] = G[i][j] ;
31+
for(i=0 ; i<n ; i++)
32+
{
33+
distance[i] = cost[startnode][i] ;
34+
pred[i] = startnode ;
35+
visited[i] = 0 ;
36+
}
37+
distance[startnode] = 0 ;
38+
visited[startnode] = 1 ;
39+
count = 1 ;
40+
while(count<n-1)
41+
{
42+
mindistance = INFINITY ;
43+
for(i=0 ; i<n ; i++)
44+
if(distance[i]<mindistance&&!visited[i])
45+
{
46+
mindistance = distance[i] ;
47+
nextnode = i ;
48+
}
49+
visited[nextnode] = 1 ;
50+
for(i=0 ; i<n ; i++)
51+
if(!visited[i])
52+
if(mindistance+cost[nextnode][i]<distance[i])
53+
{
54+
distance[i] = mindistance+cost[nextnode][i] ;
55+
pred[i] = nextnode ;
56+
}
57+
count++ ;
58+
}
59+
for(i=0 ; i<n ; i++)
60+
if(i!=startnode)
61+
{
62+
cout<<"\nDistance of node "<<i<<" : "<<distance[i] ;
63+
cout<<"\nPath : "<<i ;
64+
j=i ;
65+
do
66+
{
67+
j = pred[j] ;
68+
cout<<"<-"<<j ;
69+
}while(j!=startnode) ;
70+
}
71+
}
72+

0 commit comments

Comments
 (0)