Search:

Submit Article

# Prims algorithm for minimum spanning tree

Posted By: Easy Tutor     Category: C++ Programming     Views: 41296

## Code for Prims algorithm for minimum spanning tree in C++ Programming

```#include <iostream.h>
#include <conio.h>
#define ROW 7
#define COL 7
#define infi 5000  //infi for infinityclass prims
{
int graph[ROW][COL],nodes;
public:
prims();
void createGraph();
void primsAlgo();
};

prims :: prims(){
for(int i=0;i<ROW;i++)
for(int j=0;j<COL;j++)
graph[i][j]=0;
}

void prims :: createGraph(){
int i,j;
cout<<"Enter Total Nodes : ";
cin>>nodes;
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
cin>>graph[i][j];

for(j=0;j<nodes;j++){
if(graph[i][j]==0)
graph[i][j]=infi;
}
}
}

void prims :: primsAlgo(){
int selected[ROW],i,j,ne; //ne for no. of edgesintfalse=0,true=1,min,x,y;

for(i=0;i<nodes;i++)
selected[i]=false;

selected[0]=true;
ne=0;

while(ne < nodes-1){
min=infi;

for(i=0;i<nodes;i++)
{
if(selected[i]==true){
for(j=0;j<nodes;j++){
if(selected[j]==false){
if(min > graph[i][j])
{
min=graph[i][j];
x=i;
y=j;
}
}
}
}
}
selected[y]=true;
cout<<"\n"<<x+1<<" --> "<<y+1;
ne=ne+1;
}
}

void main(){
prims MST;
clrscr();
cout<<"\nPrims Algorithm to find Minimum Spanning Tree\n";
MST.createGraph();
MST.primsAlgo();
getch();
}```
Share:

Didn't find what you were looking for? Find more on Prims algorithm for minimum spanning tree Or get search suggestion and latest updates.

 Easy Tutor author of Prims algorithm for minimum spanning tree is from United States. Easy Tutor says Hello Friends,I am Free Lance Tutor, who helped student in completing their homework. I have 4 Years of hands on experience on helping student in completing their homework. I also guide them in doing their final year projects.I have share many programs on this website for everyone to use freely, if you need further assistance, than please contact me on easytutor.2ya [at the rate] gmail [dot] comI have special discount scheme for providing tutor services. I am providing tutor service to students from various contries, currently most of my students are from United States, India, Australia, Pakistan, Germany, UK and Canada. I am also here to expand my technical network to receive more opportunity in my career, make friends to help them in resolving their technical problem, learn and share my knowledge, If you like to be my friend, Please send me friend request.Thanks,Happy Programming :) View All Articles