0% found this document useful (0 votes)
108 views

Write C++ Programs To Implement The Prim's Algorithm To Generate A Minimum Cost Spanning Tree

The document describes a C++ program that implements Prim's algorithm to find a minimum cost spanning tree for a graph. The program takes in the number of vertices and edges as input, along with the costs of each edge. It initializes data structures to track visited vertices and edge costs. The algorithm then iteratively selects the lowest cost edge connected to a visited vertex, adds it to the spanning tree, and marks the vertex as visited, until all vertices are visited. The output prints the order of visited vertices.

Uploaded by

Kishore Khsgas K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views

Write C++ Programs To Implement The Prim's Algorithm To Generate A Minimum Cost Spanning Tree

The document describes a C++ program that implements Prim's algorithm to find a minimum cost spanning tree for a graph. The program takes in the number of vertices and edges as input, along with the costs of each edge. It initializes data structures to track visited vertices and edge costs. The algorithm then iteratively selects the lowest cost edge connected to a visited vertex, adds it to the spanning tree, and marks the vertex as visited, until all vertices are visited. The output prints the order of visited vertices.

Uploaded by

Kishore Khsgas K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

/* Write C++ programs to implement the Prims 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

You might also like