Prim’s algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the subset of the edges of that graph which
- form a tree that includes every vertex
- has the minimum sum of weights among all the trees that can be formed from the graph
How Prim’s algorithm works
It falls under a class of algorithms called Greedy Algorithm that find the local optimum in the hopes of finding a global optimum.
We start from one vertex and keep adding edges with the lowest weight until we reach our goal.
The steps for implementing Prim’s algorithm are as follows:
- Initialize the minimum spanning tree with a vertex chosen at random.
- Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree
- Keep repeating step 2 until we get a minimum spanning tree
Implementation of Prim’s Algorithm:
#include <iostream>
#define V 8
#define I 32767
using namespace std;
void PrintMST(int T[][V-2], int G[V][V]){
cout << "\nMinimum Spanning Tree Edges (w/ cost)\n" << endl;
int sum {0};
for (int i {0}; i<V-2; i++){
int c = G[T[0][i]][T[1][i]];
cout << "[" << T[0][i] << "]---[" << T[1][i] << "] cost: " << c << endl;
sum += c;
}
cout << endl;
cout << "Total cost of MST: " << sum << endl;
}
void PrimsMST(int G[V][V], int n){
int u;
int v;
int min {I};
int track [V];
int T[2][V-2] {0};
// Initial: Find min cost edge
for (int i {1}; i<V; i++){
track[i] = I; // Initialize track array with INFINITY
for (int j {i}; j<V; j++){
if (G[i][j] < min){
min = G[i][j];
u = i;
v = j;
}
}
}
T[0][0] = u;
T[1][0] = v;
track[u] = track[v] = 0;
// Initialize track array to track min cost edges
for (int i {1}; i<V; i++){
if (track[i] != 0){
if (G[i][u] < G[i][v]){
track[i] = u;
} else {
track[i] = v;
}
}
}
// Repeat
for (int i {1}; i<n-1; i++){
int k;
min = I;
for (int j {1}; j<V; j++){
if (track[j] != 0 && G[j][track[j]] < min){
k = j;
min = G[j][track[j]];
}
}
T[0][i] = k;
T[1][i] = track[k];
track[k] = 0;
// Update track array to track min cost edges
for (int j {1}; j<V; j++){
if (track[j] != 0 && G[j][k] < G[j][track[j]]){
track[j] = k;
}
}
}
PrintMST(T, G);
}
int main() {
int cost [V][V] {
{I, I, I, I, I, I, I, I},
{I, I, 25, I, I, I, 5, I},
{I, 25, I, 12, I, I, I, 10},
{I, I, 12, I, 8, I, I, I},
{I, I, I, 8, I, 16, I, 14},
{I, I, I, I, 16, I, 20, 18},
{I, 5, I, I, I, 20, I, I},
{I, I, 10, I, 14, 18, I, I},
};
int n = sizeof(cost[0])/sizeof(cost[0][0]) - 1;
PrimsMST(cost, n);
return 0;
}
Leave a comment