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

LAB4 Dijkstra's Algorithm

The document outlines a C/C++ program that implements Dijkstra's algorithm to find the shortest paths from a given vertex in a weighted connected graph to other vertices. It includes the algorithm, program code, input data, and output results demonstrating the shortest distances. The program successfully computes and displays the shortest paths based on user input for the graph and source node.

Uploaded by

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

LAB4 Dijkstra's Algorithm

The document outlines a C/C++ program that implements Dijkstra's algorithm to find the shortest paths from a given vertex in a weighted connected graph to other vertices. It includes the algorithm, program code, input data, and output results demonstrating the shortest distances. The program successfully computes and displays the shortest paths based on user input for the graph and source node.

Uploaded by

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

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.
Aim: to find shortest paths from a given vertex in a weighted connected graph to other vertices using Dijkstra's algorithm.
Algorithm:

Program:

#include<stdio.h>
#define INF 999
void dijkstra(int c[10][10],int n,int s,int d[10])
{
int v[10],min,u,i,j;
for(i=1; i<=n; i++)
{
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1; i<=n; i++)
{
min=INF;
for(j=1; j<=n; j++)
if(v[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
v[u]=1;
for(j=1; j<=n; j++)
if(v[j]==0 && (d[u]+c[u][j])<d[j])
d[j]=d[u]+c[u][j];
}
}
int main()
{
int c[10][10],d[10],i,j,s,sum,n;
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d",&c[i][j]);
printf("\nEnter the souce node:");
scanf("%d",&s);
dijkstra(c,n,s,d);
for(i=1; i<=n; i++)
printf("\nShortest distance from %d to %d is %d",s,i,d[i]);
return 0;
}

Input:

Output:
Enter n value:5
Enter the graph data:
0 3 999 7 999
3 0 4 2 999
999 4 0 5 6
72504
999 999 6 4 0
Enter the souce node:1
Shortest distance from 1 to 1 is 0
Shortest distance from 1 to 2 is 3
Shortest distance from 1 to 3 is 7
Shortest distance from 1 to 4 is 5
Shortest distance from 1 to 5 is 9
Conclusion:
Thus the program was executed sucessfully.

You might also like