Prism’s algorithm
/*5. Represent graph using adjacency list or matrix and generate minimum spanning
tree using Prism’s algorithm
*/
//********* This program works for small programs less than 10 nodes *************//
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#define inf 999
class graph
{
public:
int a[10][10],i,j,k,min,total,v,e,wt;
graph();
void create();
void prims();
};
graph::graph()
{
for(i=0;i<10;i++)
for(j=0;j<10;j++)
a[i][j]=inf;
total=0;
}
void graph::create()
{
cout<<"\nEnter no of vertices : ";
cin>>v;
cout<<"\nEnter no of edges ; ";
cin>>e;
for(i=0;i<e;i++)
{
cout<<"\nEnter edge n wt: "<<i+1<<" : ";
cin>>j>>k>>wt;
a[j][k]=a[k][j]=wt;
}
}
void graph::prims()
{
int visit[10]={0};
for(i=0;i<=v;i++)
{
for(j=0;j<=v;j++)
if(min>a[i][j])
if(!visit[i]||!visit[j])
min=a[i][j];
for(k=0;k<v;k++)
{
if(a[i][k]==min)
{
visit[i]=visit[k]=1;
cout<<"\n("<<i<<" <-> "<<k<<") "<<a[i][k];
if(min!=inf)
total=total+min;
}
}
min=inf;
}
cout<<"\nMinimum distance = "<<total;
}
void main()
{
graph obj;
clrscr();
obj.create();
obj.prims();
getch();
}
/*
OUTPUT
Enter no of vertices : 5
Enter no of edges : 7
Enter edge n wt: 1 : 1 2 3
Enter edge n wt: 2 : 2 3 2
Enter edge n wt: 3 : 3 4 1
Enter edge n wt: 4 : 4 5 5
Enter edge n wt: 5 : 5 1 4
Enter edge n wt: 6 : 1 3 5
Enter edge n wt: 7 : 1 4 7
(1 <-> 2) 3
(2 <-> 3) 2
(3 <-> 4) 1
(5 <-> 1) 4
Minimum distance = 10
*/
0 comments:
Post a Comment