/* Write C++ programs to implement the Prim’s algorithm to generate a minimum cost spanning tree */
#include<iostream> #include<conio.h> #include<stdlib.h> using namespace std; int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10],u; main() { int m,c; cout <<"enterno of vertices"; cin >> n; cout <<"ente no of edges"; cin >> m; cout <<"\nEDGES Cost\n"; for(k=1;k<=m;k++) { cin >>i>>j>>c; cost[i][j]=c; } for(i=1;i<=n;i++) for(j=1;j<=n;j++) if(cost[i][j]==0) cost[i][j]=31999; cout <<"ORDER OF VISITED VERTICES"; k=1; while(k<n) { m=31999; if(k==1) { for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(cost[i][j]<m) { m=cost[i][j]; u=i; } } else { for(j=n;j>=1;j--) if(cost[v][j]<m && visited[j]!=1 && visit[j]!=1) { visit[j]=1; stk[top]=j; top++; m=cost[v][j]; u=j; } } cost[v][u]=31999; v=u; cout<<v << " "; k++; visit[v]=0; visited[v]=1; } }
OUTPUT
enterno of vertices7
ente no of edges9
EDGES Cost
1 6 10
6 5 25
5 4 22
4 3 12
3 2 16
2 7 14
5 7 24
4 7 18
1 2 28
ORDER OF VISITED VERTICES1 6 5 4 3 2
Description :
This is the one stop educational site for all Electronic and Computer students. If you want to learn something new then we are here to help. We work on Microcontroller projects, Basic Electronics, Digital electronics, Computer projects and also in basic c/c++ programs.
#Home #Sitemap #Submit #Terms of Use
Copyright©2011 electrofriends.com All Rights Reserved
Contact:info@electrofriends.com | Powered by Dhyeya
why m=31999 ????
cost[v][u]=31999 ??
When m=31999 in the beginning it ensures that when the condition for minimum weight is checked for the first time, that particular weight will be definitely less than 31999, so it will replace 31999 as the current min weight.
why you should assign m=31999?????
absolutely wrong program…
hello……..
i need hel of this program in my assignment so please anyone can tell me, Is this program is ok or not………..
yea.. its ryt
this program isn’t working =( show result like 1 3 5 9 9 9 9 9 or smth like that…=(
it is working normally just for author’s example
@mythili
we will take max possible cost for the edges which are not really there in graph,as cost is assigned as a datatype of int we will take max possiible value in int datatypei.e.
31999
This is wrong Program
u had done a great work…………….god bless u……………………..
thanks for the programs.
error in the program
yes doesnt work! its working wrong.
something like 1 2 2 2 !
what is namespace std?
why your use cost[i][j]=31999;
why your not find the total minimum cost?
i want total cost.
this program is not working correctly..
this program is not visiting all the nodes/vertices which a spanning tree must.