#include<iostream>
using namespace std;
#define infi 9999;
class prim
{
float arr[10][10];
int nodes;
char a[6] = {'A','B','C','D','E','F'};
public:
void creategraph()
{
cout<<"ENTER THE NUMBER OF NODES : ";
cin>>nodes;
for( int i = 0 ; i < nodes ; i++ )
{
for( int j = 0 ; j < nodes ; j++)
{
if( i != j && i < j )
{
cout<<"DISTANCE BETWEEN "<<a[i]<<" TO "<<a[j]<<" = ";
cin>>arr[i][j];
arr[j][i] = arr[i][j];
}
else if(i == j)
{
arr[i][j] = 0;
}
}
}
for(int i = 0 ; i < nodes ; i++)
for(int j = 0 ; j < nodes ; j++)
if( arr[i][j] == 0 )
arr[i][j] = infi;
}
void primalgo()
{
creategraph(); // call to creategraph
int visited[nodes]; // defines which nodes are visited and from these nodes we need to find the minimum path
float min = 0, ne = 0; //minimun to find the minimum edge from the nodes and ne = number of edges
int x,y,i,j; // i and j loop variables. x and y to store value of i and j where min values occur in graph
float cost = 0; // Store minimum cost
// Initially no node is visited
for( int i = 0 ; i < nodes ; i++)
{
visited[i] = 0;
}
//visiting 1st node
visited[0] = 1;
// Number of edges in a Minimum Spanning Tree is nodes - 1
while( ne < nodes - 1)
{
min = infi; // inorder to find minimum value or else min = 0 will always be the min.
//loop for all the visited node so we determine minimum distance from all visited node
for(int i = 0 ; i < nodes ; i++)
{
if( visited[i] == 1)
{
//loop for all the un-visited node so we determine the node to be visited next to get minimum dist.
for(int j = 0 ; j < nodes ; j++)
{
if( visited[j] == 0)
{
if( min > arr[i][j] )
{
min = arr[i][j];
x = i;
y = j;
}
}
}
}
}
visited[y] = 1;
cost += min;
ne++;
cout<<a[x]<<"-->"<<a[y]<<endl;
}
cout<<endl<<"MINIMUM COST = "<<cost<<endl;
}
};
int main()
{
prim p;
p.primalgo();
return 0;
}
Comments
Post a Comment