Shortest Path Routing Algorithm


#include<stdio.h>
#include<conio.h>
#include<limits.h>
#define MAXNODE 10
#define PERM 1
#define TENT 2
#define infinity 10000
typedef struct NODELABEL
{
int predecessor;
int length;
int label;
}
NODELABEL;
int shortpath(a,n,s,t,path,dist)
int a[MAXNODE][MAXNODE],n,s,t,path[MAXNODE],*dist;
{
NODELABEL state[MAXNODE];
int i,k,min,count;
int rpath[MAXNODE];
*dist=0;
for(i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].length=infinity;
state[i].label=TENT;
}
state[s].predecessor=0;
state[s].length=0;
state[s].label=PERM;
k=s;
do
{
for(i=1;i<=n;i++)
{
if(a[k][i]>0&&state[i].label==TENT)
{
if(state[k].length+a[k][i]<state[i].length)
{
state[i].predecessor=k;
state[i].length=state[k].length+a[k][i];
}
}
}
min=infinity;
k=0;
for(i=1;i<=n;i++)
{
if(state[i].label==TENT&&state[i].length<min)
{
min=state[i].length;
k=i;
}
}
if(k==0)
return(0);
state[k].label=PERM;
}
while(k!=t);
k=t;
count=0;
do
{
count=count+1;
rpath[count]=k;
k=state[k].predecessor;
}
while(k!=0);
for(i=1;i<=count;i++)
path[i]=rpath[count-i+1];
for(i=1;i<count;i++)
*dist+=a[path[i]][path[i+1]];
return(count);
}
void main()
{
int a[MAXNODE][MAXNODE],i,j;
int path[MAXNODE];
int from,to,dist,count,n;
printf("\n how many nodes \n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter node %d connectivity ",i);
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n from to where?");
scanf("%d%d",&from,&to);
count=shortpath(a,n,from,to,path,&dist);
if(dist)
{
printf("\n shortest path \n");
printf("%d",path[1]);
for(i=2;i<=count;i++)
printf("-->%d",path[i]);
printf("\n minimum distance=%d \n",dist);
}
else
printf("\n path does not exist \n");
}

No comments:

My Favorite Books

  • C and Data Structures by Ashok N. kamthane
  • Web Technologies by A. A. Puntambekar
  • Learn HTML and CSS with W3Schools
  • Learn JavaScript and Ajax with W3Schools
  • HTML5 Black Book: Covers Css3, Javascript,XML, XHTML, Ajax, PHP And Jquery
  • HTML5 Application Development Fundamentals: MTA Exam 98-375
  • .NET 4.0 Programming 6-In-1, Black Book
  • SQL Server 2008 R2 Black Book
  • Asp.net 4.0 Projects Covers: net 3.5 And .net 4.0 Codes, Black Book
  • UNIX Shell Programming 1 Edition by Yashavant Kanetkar
  • UNIX and Shell Programming 1 Edition by Richard F. Gilberg, Behrouz A. Forouzan
  • Computer Networks by Andrew S. Tanenbaum
  • Multiple Choice questions in computer science by Timothy J Williams