Prim’s algorithm is a greedy algorithm that finds the minimum spanning tree (MST) for a weighted undirected graph. It starts with a single vertex and grows the MST one edge at a time by adding the smallest edge that connects a vertex in the MST to a vertex outside the MST.
In this article, we will learn we will learn working of prim's algorithm, how to implement prim's algorithm in C and its applications.
Prim's Algorithm for Minimum Spanning Tree (MST) in C
Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree for a particular weighted undirected graph. It finds the subset of the edges of a graph which can include each vertex and adds the value of the edges to minimize them. It starts with a single node and evaluates all adjacent nodes that connect the present edges in every evaluation stage.
Principle of Prim’s Algorithm
Prim’s algorithm works by maintaining two sets of vertices:
- Vertices included in the MST.
- Vertices not yet included in the MST.
At each step, it 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
Following is the algorithm for finding the minimum spanning tree of a graph using Prim's algorithm:
- Declare an array parent[] to keep track of the minimum spanning tree.
- Declare an array named weights[] to store minimum weights and visited[] to keep track of the visited nodes.
- Initialize weights to infinity and parents to 0 initially for all nodes.
- Start with the 0th node and mark parent[0] as -1 and set the weight[0] as 0 as it is the initial vertex.
- For each vertex u with minimum weight not yet included in the MST:
- Include vertex in MST by updating visited[u] as true.
- For each adjacent vertex v of u:
- If graph[u][v] is non-zero and visited[v] is false and the edge doesn't forms a cycle:
- Update weight[v] and parent[v] if graph[u][v] is smaller than weight[v].
- Repeat the above steps until all the vertices are included in the MST.
- Use the parent[] array to print the constructed array.
- Use the weights[] array to print the total minimal cost of the constructed MST.
Working of Prim's Algorithm
Let us consider the following example of weighted undirected graph and see how Prim's algorithm will generate the minimum spanning tree(MST) for it step-by-step:
C Program for Implementation of Prim’s Algorithm
The following program illustrates the implementation of Prim's algorithm in C.
C
// C Program to Implement Prim's Algorithm
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
// Define Number of vertices in the graph
#define V 5
// Function to find the vertex with the minimum weight
int minweight(int weight[], bool visited[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (visited[v] == false && weight[v] < min) {
min = weight[v];
min_index = v;
}
}
return min_index;
}
// Function to print the constructed MST and its total cost
void printMST(int parent[], int graph[V][V])
{
int totalCost = 0;
printf("MST for the graph:\n");
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i,
graph[i][parent[i]]);
totalCost += graph[i][parent[i]];
}
printf("Total cost of MST: %d\n", totalCost);
}
// Function to construct and print MST for a graph
// represented using adjacency matrix representation
void primMST(int graph[V][V])
{
// Array to store constructed MST
int parent[V];
// Array to store the weights
int weight[V];
// To represent set of vertices included in MST
bool visited[V];
// Initialize all weights as INFINITE
for (int i = 0; i < V; i++) {
weight[i] = INT_MAX;
visited[i] = false;
}
// Always include the first 1st vertex in MST.
weight[0] = 0;
parent[0] = -1;
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum weight vertex from the set of
// vertices not yet included in MST
int u = minweight(weight, visited);
// Add the picked vertex to the MST Set
visited[u] = true;
// Consider only those vertices which are not yet
// included in MST
for (int v = 0; v < V; v++) {
if (graph[u][v] && visited[v] == false
&& graph[u][v] < weight[v]) {
parent[v] = u;
weight[v] = graph[u][v];
}
}
}
// Print the constructed MST and its total cost
printMST(parent, graph);
}
int main()
{
/* Let us create the following graph
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int graph[V][V] = { { 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 } };
// Print the MST
primMST(graph);
return 0;
}
OutputMST for the graph:
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
Total cost of MST: 16
Time Complexity: O(V2), If the input graph is represented using an adjacency list, then the time complexity of Prim’s algorithm can be reduced to O(E * logV) with the help of a binary heap. In this implementation, we are always considering the spanning tree to start from the root of the graph
Auxiliary Space: O(V)
Applications of Prim's Algorithm
Following are some common applications of Prims Algorithm:
- Network Design: Used in networking to minimize the costs in telecommunication and computer networks.
- Transportation: Used for planning road, highway, and railway networks with minimal total length.
- Computer Graphics: Used in image segmentation and 3D mesh generation in an optimized way.
- Game Development: Used for generating natural-looking mazes and terrains with minimal cost.
- VLSI Design: Used for reducing wiring lengths in very large scale integration circuits.
Related Articles:
You can also go through some other implementations of Prim’s Algorithm: