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:
Similar Reads
Prim's Algorithm in C++
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
6 min read
Kahnâs Algorithm in C Language
In this post, we will see the implementation of Kahn's Algorithm in C language.What is Kahn's Algorithm?The Kahn's Algorithm is a classic algorithm used to the perform the topological sorting on the Directed Acyclic Graph (DAG). It produces a linear ordering of the vertices such that for every direc
5 min read
Tarjanâs Algorithm in C Language
In this post, we will see the implementation of Tarjan's Algorithm in C language.What is Tarjan's Algorithm?Tarjan's Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every oth
5 min read
Convex Hull Algorithm in C
The Convex Hull problem is a fundamental computational geometry problem, where the goal is to find the smallest convex polygon called convex hull that can enclose a set of points in a 2D plane. This problem has various applications, such as in computer graphics, geographic information systems, and c
15+ min read
CSES Solutions - Weird Algorithm
Consider an algorithm that takes as input a positive integer N. If N is even, the algorithm divides it by two, and if N is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until N is one. Your task is to simulate the execution of the algorithm for a given value of
4 min read
C++ Pointer Arithmetic
In C++, pointer arithmetic means performing arithmetic operations on pointers. It refers to the operations that are valid to perform on pointers. Following are the arithmetic operations valid on pointers in C++:Table of ContentIncrementing and Decrementing Pointer in C++Addition of Constant to Point
7 min read
Implementation of Rabin Karp Algorithm in C++
The Rabin-Karp Algorithm is a string-searching algorithm that efficiently finds a pattern within a text using hashing. It is particularly useful for finding multiple patterns in the same text or for searching in streams of data. In this article, we will learn how to implement the Rabin-Karp Algorith
5 min read
Boyer-Moore Algorithm for Pattern Searching in C
In this article, we will learn the Boyer-Moore Algorithm, a powerful technique for pattern searching in strings using C programming language. What is the Boyer-Moore Algorithm?The Boyer-Moore Algorithm is a pattern searching algorithm that efficiently finds occurrences of a pattern within a text. It
7 min read
Trial division Algorithm for Prime Factorization
In this article, the trial division method to check whether a number is a prime or not is discussed. Given a number N, the task is to check whether the number is prime or not. Examples: Input: N = 433 Output: Prime Explanation: The only factors of 433 are 1 and 433. Therefore, it is a prime. Input:
7 min read
C Program for KMP Algorithm for Pattern Searching
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST"Output: Pattern found at index 10Input: txt[] = "AABAACAADAABA
3 min read