C - Program to Implement Prims Algorithm
#include<iostream.h>
#include<conio.h>
#include<time.h>
#define infinity 9999
int g[20][20],nodes;
void prims();
void getgraph();
int main()
{
int i;
char k='y';
do
{
clrscr();
float toc;
clock_t end,start;
start=clock();
cout<<"\n\t\t\t\tPrims Algorithm";
cout<<"\n\t\t\t\t---------------";
getgraph();
prims();
end=clock();
toc=(end - start)/CLK_TCK;
cout<<"\n\n\t\tTime Complexity :: "<<toc;
cout<<"\n\n\t\t\tDo u want to continue?(y/n)";
k=getche();
}while(k=='y');
return 0;
}
void getgraph()
{
int i,j,k,n,v1,v2,len;
cout<<"\n\n\t\tEnter the Number of Nodes in Graph :: ";
cin>>nodes;
cout<<"\n\t\tEnter the Number of Edges in Graph ::";
cin>>n;
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
g[i][j]=0;
for(i=0;i<n;i++)
{
cout<<"\n\t\tEnter Edges (V1,V2) ::";
cin>>v1>>v2;
cout<<"\n\t\tEnter the Corresponding Weight :: ";
cin>>len;
g[v1][v2]=g[v2][v1]=len;
}
}
void prims()
{
int tree[20],i,j,k;
int min,tot,v1,v2;
tot=0;
for(i=0;i<nodes;i++)
tree[i]=0;
cout<<"\n\t\tMinimal Spanning Tree is :: ";
tree[0]=1;
for(k=1;k<=nodes-1;k++)
{
min=infinity;
for(i=0;i<=nodes-1;i++)
{
for(j=0;j<=nodes-1;j++)
{
if(g[i][j] &&((tree[i] && !tree[j])||(!tree[i] && tree[j])))
{
if(g[i][j]<min)
{
min=g[i][j];
v1=i;
v2=j;
}
}
}
}
cout<<"\n\n\t\tEdge ("<<v1<<","<<v2<<")";
cout<<"\tWeight = "<<min;
tree[v1]=tree[v2]=1;
tot=tot + min;
}
cout<<"\n\n\t\tTotal Path Length :: "<<tot;
}
#include<conio.h>
#include<time.h>
#define infinity 9999
int g[20][20],nodes;
void prims();
void getgraph();
int main()
{
int i;
char k='y';
do
{
clrscr();
float toc;
clock_t end,start;
start=clock();
cout<<"\n\t\t\t\tPrims Algorithm";
cout<<"\n\t\t\t\t---------------";
getgraph();
prims();
end=clock();
toc=(end - start)/CLK_TCK;
cout<<"\n\n\t\tTime Complexity :: "<<toc;
cout<<"\n\n\t\t\tDo u want to continue?(y/n)";
k=getche();
}while(k=='y');
return 0;
}
void getgraph()
{
int i,j,k,n,v1,v2,len;
cout<<"\n\n\t\tEnter the Number of Nodes in Graph :: ";
cin>>nodes;
cout<<"\n\t\tEnter the Number of Edges in Graph ::";
cin>>n;
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
g[i][j]=0;
for(i=0;i<n;i++)
{
cout<<"\n\t\tEnter Edges (V1,V2) ::";
cin>>v1>>v2;
cout<<"\n\t\tEnter the Corresponding Weight :: ";
cin>>len;
g[v1][v2]=g[v2][v1]=len;
}
}
void prims()
{
int tree[20],i,j,k;
int min,tot,v1,v2;
tot=0;
for(i=0;i<nodes;i++)
tree[i]=0;
cout<<"\n\t\tMinimal Spanning Tree is :: ";
tree[0]=1;
for(k=1;k<=nodes-1;k++)
{
min=infinity;
for(i=0;i<=nodes-1;i++)
{
for(j=0;j<=nodes-1;j++)
{
if(g[i][j] &&((tree[i] && !tree[j])||(!tree[i] && tree[j])))
{
if(g[i][j]<min)
{
min=g[i][j];
v1=i;
v2=j;
}
}
}
}
cout<<"\n\n\t\tEdge ("<<v1<<","<<v2<<")";
cout<<"\tWeight = "<<min;
tree[v1]=tree[v2]=1;
tot=tot + min;
}
cout<<"\n\n\t\tTotal Path Length :: "<<tot;
}