Sunday, December 12, 2010

Prim's Algorithm

//Program to illustrate Prims Algorithm
#include
#include
#include

class prims
{
int i,j,k,l,n;
int w[20][20],low;
char node[26],c,d;
public:
prims()
{
low=9999;
}
void read();
void disp();
void prim();
};

//function reads elements
void prims::read()
{
cout<<"Entrer the no of nodes:";
cin>>n;
if(n==1)
{
cout<<"Only one vertex.\n";
return;
}
cout<<"Enter the nodes:";
for(i=1;i<=n;i++)
cin>>node[i];
cout<<"Enter the weight of matrix:";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cin>>w[i][j];
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(w[i][j]==0)
w[i][j]=9999;
}


//function to calculate minimum spanning tree
void prims::prim()
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(w[i][j] {
low=w[i][j];
k=j;
}
else
w[i][j]=0;
}
j=j-1;
for(l=1;l<=n;l++)
{
if(l!=k)
w[i][l]=0;
}
low=9999;
}
}


//function to display tree
void prims::disp()
{
int p,q;
cout<<"\nMinimal spanning tree:\n";
for(p=1;p<=n;p++)
{
for(q=1;q<=n;q++)
{
if(w[p][q]!=0)
{
if(w[p][q]==w[q][p])
w[p][q]=w[q][p]=0;
cout< }
}
}
}


void main()
{
prims p;
clrscr();
cout<<”PRIM’S ALGORITHM\n-----------------------------\n”;
p.read();
p.prim();
p.disp();
getch();
}


OUTPUT


PRIM'S ALGORITHM
--------------------------------

Entrer the no of nodes:5
Enter the nodes:a b c d e
Enter the weight of matrix:
0 2 8 0 0
2 0 3 5 0
8 3 0 7 4
0 5 7 0 0
0 0 4 0 0

Minimal spanning tree:
a-b
c-b
d-b
e-c

No comments:

Post a Comment