Program 4
Program 4
Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted
connected graph to other vertices using Dijkstra's algorithm.
#include<stdio.h>
void main()
{
int i,j,a[10][10],s[10],n,d[10],v,k,min,u;
for(i=1;i<=n;i++)
{
s[i]=0;
d[i]=a[v][i];
}
d[v]=0;
s[v]=1;
for(k=2;k<=n;k++)
{
min=999;
for(i=1;i<=n;i++)
if(s[i]==0&&d[i]<min)
{
min=d[i];
u=i;
}
s[u]=i;
for(i=1;i<=n;i++)
if(s[i]==0)
{
if(d[i]>d[u]+a[u][i])
d[i]=d[u]+a[u][i];
}
}
printf("the shortest distance from %d is\n",v);
for(i=1;i<=n;i++)
printf("\n%d->%d=%d",v,i,d[i]);
}
Sample Input and Output:
enter the no of vertices:=>5
enter the cost matrix
enter 999 for no edges between vertices
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
enter the source vertex
1
the shortest distance from 1 is
1->1=0
1->2=3
1->3=7
1->4=5
1->5=9