0% found this document useful (0 votes)
2 views2 pages

Djikstra Algorithm

The document describes Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a network of cities. It includes a C program implementation that prompts the user for the number of vertices, a cost matrix, and a source vertex, then calculates and displays the shortest distances. A sample output is mentioned but not provided in detail.

Uploaded by

geetha sree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Djikstra Algorithm

The document describes Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a network of cities. It includes a C program implementation that prompts the user for the number of vertices, a cost matrix, and a source vertex, then calculates and displays the shortest distances. A sample output is mentioned but not provided in detail.

Uploaded by

geetha sree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Djikstra’s algorithm (Single source shortest path)

It finds the shortest path from a given source vertex to all the other
vertices
12. Suppose a travel agent is interested in finding shortest path from a single city to all the other cities in a
network of ‘n’ cities. Write a C program to implement this using Djikstra’s algorithm.

#include <stdio.h>

void main()
{
int n,i,j,a[10][10],s[10],d[10],v,k,min,u;
printf("Enter the number of vertices\n");
scanf("%d",&n);
printf("Enter the cost matrix \n");
printf("Enter 999 if no edge between vertices \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("Enter the source vertex \n");
scanf("%d",&v);
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]=1;
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("%d-->%d=%d\n",v,i,d[i]);
}

SAMPLE OUTPUT for the following graph:

You might also like