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

Program 4

This document provides a C/C++ program that implements Dijkstra's algorithm to find the shortest paths from a given vertex in a weighted connected graph. It includes user input for the number of vertices and the cost matrix, as well as the source vertex. The program outputs the shortest distances from the source vertex to all other vertices in the graph.

Uploaded by

abhinehalove71
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)
3 views2 pages

Program 4

This document provides a C/C++ program that implements Dijkstra's algorithm to find the shortest paths from a given vertex in a weighted connected graph. It includes user input for the number of vertices and the cost matrix, as well as the source vertex. The program outputs the shortest distances from the source vertex to all other vertices in the graph.

Uploaded by

abhinehalove71
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

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;

printf("enter the no of vertices:=>");


scanf("%d",&n);

printf("enter the cost matrix\n");


printf("enter 999 for no edges 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]=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

You might also like