Prim's Algorithm

AIM: To implement Prim’s algorithm to generate a minimum cost spanning tree.
SOURCE CODE:
#include <iostream>
#include<limits.h>
using namespace std;
int minKey(int key[], bool mstSet[],int V)
{
    int min = INT_MAX, min_index;
    for (int v = 0; v < V; v++)
        if (mstSet[v] == false && key[v] < min)
            min = key[v], min_index = v;
    return min_index;
}
int printMST(int parent[], int V, int graph[20][20])
{
    int cost=0;
    cout<<"Edge\t\tWeight"<<endl;
    for (int i = 1; i < V; i++){
        cout<<parent[i]<<"->"<<i<<"\t\t"<<graph[i][parent[i]]<<endl;
        cost=cost+graph[i][parent[i]];
    }
    cout<<"Cost of spanning-tree is :"<<cost<<endl;
    return 0;
}
void primMST(int graph[20][20],int V)
{
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V-1; count++)
{
int u = minKey(key, mstSet,V);
mstSet[u] = true;
for (int v = 0; v < V; v++)
            if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
                parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, V, graph);
}
int main()
{
    int graph[20][20],V,i,j;
    cout<<"Enter number of vertices:"<<endl;
    cin>>V;
    cout<<"Enter weights of each edge between two vertices:"<<endl;
    for(i=0;i<V;i++)
        for(j=0;j<V;j++)
            cin>>graph[i][j];
    primMST(graph,V);
    return 0;
}
OUTPUT:
Enter number of vertices:
5
Enter weights of each edge between two vertices:
0 2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 0 9
0 5 7 9 0
Edge Weight
0->1 2
1->2 3
0->3 6
1->4 5
Cost of spanning-tree is :16

No comments:

Post a Comment

Total Pageviews