Prim's algorithm is a greedy algorithm used to find the minimum spanning tree of a weighted undirected graph by adding edges with the smallest weights until all vertices are connected.
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <limits.h>
using namespace std;
void primsAlgorithm(int graph[V][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 minKey = INT_MAX, minIndex;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < minKey)
minKey = key[v], minIndex = v;
mstSet[minIndex] = true;
for (int v = 0; v < V; v++)
if (graph[minIndex][v] && mstSet[v] == false && graph[minIndex][v] < key[v])
parent[v] = minIndex, key[v] = graph[minIndex][v];
}
for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << endl;
}
Understanding Prim's Algorithm
What is Prim's Algorithm?
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree (MST) for a weighted undirected graph. The purpose of this algorithm is to ensure that all vertices are connected with the minimum possible total edge weight while avoiding cycles. This characteristic makes Prim’s algorithm particularly useful in scenarios such as designing networks (telecommunication, electricity, etc.) and solving various optimization problems.
Importance of Prim's Algorithm in Computer Science
In computer science and network design, Prim's algorithm plays a critical role. It is fundamental in scenarios where it is essential to connect different nodes (like computers in a network) while minimizing the cost of wiring or connecting them. Additionally, it finds applications in approximation algorithms for other complex problems, solidifying its importance in both theoretical and practical domains.

Fundamental Concepts
Graph Theory Basics
To understand Prim’s algorithm, it's crucial to grasp the basics of graph theory. A graph consists of a set of vertices (or nodes) and a set of edges connecting these vertices. The weights assigned to the edges represent the cost to traverse them, forming a pivotal part of working with the algorithm.
There are several types of graphs:
- Weighted graphs: where edges have weights (costs).
- Undirected graphs: where edges do not have a direction.
- Directed graphs: where edges indicate a direction from one vertex to another.
Minimum Spanning Tree Explained
A minimum spanning tree is a subset of the edges in a graph that connects all vertices without creating any cycles and with the minimal possible total edge weight. The MST has the following characteristics:
- Connected: All vertices must be connected.
- Acyclic: No circular paths can be formed.
- Minimal weight: The sum of the weights of the edges in the tree must be as low as possible.

How Prim's Algorithm Works
Overview of the Algorithm
Prim's algorithm starts from an arbitrary vertex and grows the MST one edge at a time. It continuously selects the smallest weight edge that connects a vertex included in the MST to a vertex outside of it, effectively expanding the MST until all vertices are included.
Breakdown of the Steps
Step 1: Initialize the Algorithm
Before diving into the process of selecting edges, Prim's algorithm requires the initialization of necessary data structures. This includes selecting a starting vertex and initializing:
- MST membership to track which vertices are included in the MST.
- Key values (minimum edge weights) to determine the next vertex to add.
- Priority queue to efficiently select the vertex with the smallest key value.
Step 2: Iterate Through Vertices
Prim's algorithm then enters a loop where the next vertex is selected by examining the edges connected to the vertices already included in the MST. The minimum-weight edge that connects to an outsider (a vertex not yet in the MST) is identified, leading to the addition of that vertex to the MST.
Step 3: Continue Until All Vertices Are Included
This process repeats until all vertices from the graph are included in the MST, resulting in a complete tree structure that connects all vertices with the least total weight.

Code Implementation of Prim's Algorithm
Setting Up the Environment
To implement Prim's algorithm in C++, you need a standard C++ compilation environment. Any modern C++ compiler will work, but ensure that you have standard libraries that provide data structures like vectors.
Code Snippet: Prim’s Algorithm Implementation
Here is a simple implementation of Prim's algorithm in C++:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <limits>
using namespace std;
#define INF numeric_limits<int>::max()
int minKey(const vector<int>& key, const vector<bool>& inMST, int n) {
int min = INF, min_index;
for (int v = 0; v < n; v++) {
if (!inMST[v] && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
void printMST(const vector<int>& parent, const vector<vector<int>>& graph) {
cout << "Edge \tWeight\n";
for (int i = 1; i < graph.size(); i++)
cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << " \n";
}
void primsAlgorithm(const vector<vector<int>>& graph, int start) {
int n = graph.size();
vector<bool> inMST(n, false);
vector<int> key(n, INF);
vector<int> parent(n, -1);
key[start] = 0;
for (int count = 0; count < n - 1; count++) {
int u = minKey(key, inMST, n);
inMST[u] = true;
for (int v = 0; v < n; v++) {
if (graph[u][v] && !inMST[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printMST(parent, graph);
}
Detailed Explanation of the Code
In this code, we define a function `minKey` to find the vertex with the smallest key that is not yet included in the MST. The main function, `primsAlgorithm`, initializes required structures, iterates through vertices to build the MST using a greedy approach, and finally calls `printMST` to display the edges of the MST.
The usage of key values and the priority queue representation through vectors allows the algorithm to efficiently select the lowest weight edges.

Advanced Concepts
Time Complexity Analysis
The time complexity of Prim's algorithm primarily depends on the data structures used. If implemented using an adjacency matrix along with a simple array for the priority queue, the time complexity is O(V^2), where V is the number of vertices. However, if a binary heap is used for the priority queue, the complexity can be reduced to O(E log V), where E is the number of edges, making it more efficient for sparse graphs.
Space Complexity Considerations
The space complexity of Prim's algorithm is O(V) due to the storage required for the arrays that track the key values, parents, and MST memberships.

Practical Applications of Prim's Algorithm
Networking
One of the most prevalent applications of Prim's algorithm is in designing efficient network layouts. For example, when laying down cables to connect a series of buildings, Prim's algorithm identifies the cheapest way to connect all locations with minimal costs.
Geographical Mapping
In geographical mapping, Prim’s algorithm is utilized to find the shortest path or minimal connections among various geographical points, leading to efficient route optimization.
Real-World Problem Solving
Several case studies demonstrate the application of Prim's algorithm in industrial and logistical problems, such as minimizing costs in transportation networks, managing power grids, and even in the structure of computer networks to enhance communication efficiency.

Conclusion
Prim's algorithm is a powerful tool in the realm of graph theory and computer science, serving essential functions in connecting nodes with optimal edge weights. By understanding "C++ Prim's Algorithm," programmers and computer scientists can apply these concepts to a wide range of practical and theoretical problems, thus enhancing their problem-solving capabilities in various domains.

Additional Resources
Recommended Reading
For further understanding, consider diving into textbooks that cover graph theory and algorithms in more depth.
Online Tutorials
Explore video tutorials and coding platforms that provide hands-on practice to solidify your understanding of Prim's algorithm and related graph algorithms.