Prim's Algorithm is a greedy algorithm that is used to find the Minimum Spanning Tree (MST) for a weighted, undirected graph. MST is a subset of the graph's edges that connects all vertices together without any cycles and with the minimum possible total edge weight
In this article, we will learn the working of Prim's Algorithm, how to implement it in C++, and its applications.
What is Prim's Algorithm for MST?
Prim’s Algorithm finds the subset of the edges in a graph that connects all vertices with the minimum total edge weight. It starts with a single vertex and grows the MST one edge at a time by maintaining the visited array.
At each step, the algorithm selects the minimum weight edge that connects a vertex in the MST to a vertex outside the MST and adds it to the MST.
Algorithm
Below are the steps to find the minimum spanning tree using prim’s algorithm:
- Create the 3 vector, key(it contains the minimum edge weight among all the edge weight of this vertex), parent( it contains the parent of the vertices), vis(it shows whether the vertices is visited or not).
- Assign all the value in the key vector is infinity except for the source vertex whose value is 0. Initialize the parent of the source vertex is -1.
- Create the min-heap and push the source vertex in to the priority queue.
- While min-heap will not become empty:
- Select the top element of the min-heap (vertex 'u') which has minimum edge weight and make this vertex true in the visited vector.
- For each vertex v adjacent to u:
- If v is not visited and the edge u-v has a weight less than the current key value of v, update key[v] to the weight of u-v.
- Continue this process until min-heap become empty, resulting in the MST.
C++ Program for Implementation of Prim’s Algorithm
The below program illustrates the implementation of Prim’s algorithm in C++.
C++
// C++ Program to implement the
// Prim's Algorithm using Adjecency matrix
#include <bits/stdc++.h>
using namespace std;
// Function to construct and print the MST
void primMST(vector<vector<int>> graph) {
int v = graph.size();
// vector to store the parent of vertex
vector<int> parent(v);
// vector holds the weight/ cost of the MST
vector<int> key(v);
// vector to represent the set of
// vertices included in MST
vector<bool> vis(v);
priority_queue<pair<int, int>,
vector<pair<int, int>>,
greater<pair<int, int>>> pq;
// Initialize all key vector as INFINITE
// and vis vector as false
for (int i = 0; i < v; i++) {
key[i] = INT_MAX;
vis[i] = false;
}
// Always include the first vertex in MST.
// Make key 0 so that this vertex is
// picked as the first vertex.
key[0] = 0;
// First node is always the root of MST
parent[0] = -1;
// Push the source vertex to the min-heap
pq.push({0, 0});
while (!pq.empty()) {
int node = pq.top().second;
pq.pop();
vis[node] = true;
for (int i = 0; i < v; i++) {
// If the vertex is not visited
// and the edge weight of neighbouring
// vertex is less than key value of
// neighbouring vertex then update it.
if (!vis[i] && graph[node][i] != 0
&& graph[node][i] < key[i]) {
pq.push({graph[node][i], i});
key[i] = graph[node][i];
parent[i] = node;
}
}
}
// Print the edges and their
// weights in the MST
cout << "Edge \tWeight\n";
for (int i = 1; i < v; i++) {
cout << parent[i] << " - " << i
<< " \t" << graph[i][parent[i]] << " \n";
}
}
int main() {
// Define the adjacency matrix
vector<vector<int>> graph = {{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}};
// Find and print the Minimum Spanning
// Tree using Prim's algorithm
primMST(graph);
return 0;
}
OutputEdge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
Time Complexity: O(V 2 ), using an adjacency matrix and O((V +E) log V) using an adjacency list, where V is the number of vertices and E is the number of edges in the graph.
Auxiliary Space: O(V )
Applications of Prim's Algorithm
Prim's Algorithm is used in various fields as it is an efficient approach to find the minimum spanning tree. Some common applications are:
- It is used in networking to minimize costs in telecommunication and computer networks.
- It helps in planning road, highway, and railway networks with minimal total length.
- It can be applied in image segmentation and 3D mesh generation.
- Used for generating natural-looking mazes and terrains.
- Used for reducing wiring lengths in very-large-scale integration circuits.