Professional Documents
Culture Documents
Vignesh
Ex.no:3a
Date:
Aim:
To write a Program to implement shortest path algorithm-Dijikstra' Algorithm
Algorithm:
1. Assign to every node a distance value. Set it to zero for our initial node and to infinity for
all other nodes.
2. Mark all nodes as unvisited. Set initial node as current.
3. For current node, consider all its unvisited neighbours and calculate their distance (from
the initial node).
4. If this distance is less than the previously recorded distance (infinity in the beginning,
zero for the initial node), overwrite the distance.
5. After considering all neighbours of the current node, mark it as visited. A visited node
will not be checked ever again; its distance recorded now is final and minimal.
6. Set the unvisited node with the smallest distance (from the initial node) as the next
"current node" and continue from step 3.
Program:
#include<iostream.h>
#include<conio.h>
struct table
{
int vno;
int known;
int dist;
int path;
}t[5];
void main()
{
int g[5][5];
int mi,i,j,s,c;
int min=0,k;
int count=0;
clrscr();
cout<<"Input to the graphin the form of weight\n";
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
Page No:
Name: M.Vignesh
{
cout<<"Enter the weight for the vertex for:<<i<<j;
cin>>g[i][j];
}
}
cout<<"Checking the Graph with its weight";
for(i=0;i<5;i++)
{
cout<<"\n";
for(j=0;j<5;j++)
{
cout<<"%d\t",g[i][j]);
}
}
cout<<"\n\t\t\tInitial Configuration\n";
for(i=0;i<5;i++)
{
t[i].vno=i;
t[i].known=0;
t[i].dist=1000;
t[i].path=0;
}
for(c=0;c<5;c++)
{
cout<<t[c].vno<<t[c].known<<t[c].dist<<t[c].path;
}
cout<<"\nSelect the source vertex:";
cin>>s;
t[s].known=1;
count=1;
t[s].dist=0;
t[s].path=0;
for(i=0;i<5;i++)
{
if(g[s][i]!=0)
{
t[i].dist=t[s].dist+g[s][i];
t[i].path=s;
}
}
//display function
for(c=0;c<5;c++)
{
cout<<t[c].vno<<t[c].known<<t[c].dist<<t[c].path;
}
//finding the Minimum Distance//
Page No:
Name: M.Vignesh
while(count!=5)
{
for(i=0;i<4;i++)
{
if(t[i].known!=1)
{
min=t[i].dist;
for(k=i;k<4;k++)
{
if(t[k+1].known!=1)
{
if(min>t[k+1].dist)
{
min=t[k+1].dist;
i=k+1;
}
}
}
cout<<"the mininmun element is %d\n"<<min;
break;
}
}
cout<<"the value of i is<<i;
t[i].known=1;
count++;
for(j=0;j<5;j++)
{
if(g[i][j]!=0 && (t[i].dist+g[i][j])<t[j].dist)
{
t[j].dist=t[i].dist+g[i][j];
t[j].path=i;
}
}
for(c=0;c<5;c++)
{
cout<<t[c].vno<<t[c].known<<t[c].dist<<t[c].path;
}
}
getch();
}
Page No:
Name: M.Vignesh
Output:
Name: M.Vignesh
0
1
2
3
4
0
0
0
0
0
Initial Configuration
1000 0
1000 0
1000 0
1000 0
1000 0
Page No:
Name: M.Vignesh
Result:
Thus the implementation of Dijikstra algorithm was written, compiled, executed and
outputs were noted.
Page No: