
- Data Structures & Algorithms
- DSA - Home
- DSA - Overview
- DSA - Environment Setup
- Data Structures
- DSA - Data Structure Basics
- DSA - Data Structures and Types
- DSA - Array Data Structure
- Linked Lists
- DSA - Linked List Data Structure
- DSA - Doubly Linked List Data Structure
- DSA - Circular Linked List Data Structure
- Stack & Queue
- DSA - Stack Data Structure
- DSA - Expression Parsing
- DSA - Queue Data Structure
- Graph Data Structure
- DSA - Graph Data Structure
- DSA - Depth First Traversal
- DSA - Breadth First Traversal
- DSA - Spanning Tree
- Tree Data Structure
- DSA - Tree Data Structure
- DSA - Tree Traversal
- DSA - Binary Search Tree
- DSA - AVL Tree
- DSA - Red Black Trees
- DSA - B Trees
- DSA - B+ Trees
- DSA - Splay Trees
- DSA - Tries
- DSA - Heap Data Structure
- Recursion
- DSA - Recursion Algorithms
- DSA - Tower of Hanoi Using Recursion
- DSA - Fibonacci Series Using Recursion
- DSA Useful Resources
- DSA - Questions and Answers
- DSA - Quick Guide
- DSA - Useful Resources
- DSA - Discussion

- Data Structures & Algorithms
- DSA - Home
- DSA - Overview
- DSA - Environment Setup
- Data Structures
- DSA - Data Structure Basics
- DSA - Data Structures and Types
- DSA - Array Data Structure
- Linked Lists
- DSA - Linked List Data Structure
- DSA - Doubly Linked List Data Structure
- DSA - Circular Linked List Data Structure
- Stack & Queue
- DSA - Stack Data Structure
- DSA - Expression Parsing
- DSA - Queue Data Structure
- Graph Data Structure
- DSA - Graph Data Structure
- DSA - Depth First Traversal
- DSA - Breadth First Traversal
- DSA - Spanning Tree
- Tree Data Structure
- DSA - Tree Data Structure
- DSA - Tree Traversal
- DSA - Binary Search Tree
- DSA - AVL Tree
- DSA - Red Black Trees
- DSA - B Trees
- DSA - B+ Trees
- DSA - Splay Trees
- DSA - Tries
- DSA - Heap Data Structure
- Recursion
- DSA - Recursion Algorithms
- DSA - Tower of Hanoi Using Recursion
- DSA - Fibonacci Series Using Recursion
- DSA Useful Resources
- DSA - Questions and Answers
- DSA - Quick Guide
- DSA - Useful Resources
- DSA - Discussion
Prim's Spanning Tree Algorithm
Prim's algorithm to find minimum cost spanning tree (as Kruskal's algorithm) uses the greedy approach. Prim's algorithm shares a similarity with the shortest path first algorithms.
Prim's algorithm, in contrast with Kruskal's algorithm, treats the nodes as a single tree and keeps on adding new nodes to the spanning tree from the given graph.
To contrast with Kruskal's algorithm and to understand Prim's algorithm better, we shall use the same example −

Step 1 - Remove all loops and parallel edges

Remove all loops and parallel edges from the given graph. In case of parallel edges, keep the one which has the least cost associated and remove all others.

Step 2 - Choose any arbitrary node as root node
In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any node can be the root node. One may wonder why any video can be a root node. So the answer is, in the spanning tree all the nodes of a graph are included and because it is connected then there must be at least one edge, which will join it to the rest of the tree.
Step 3 - Check outgoing edges and select the one with less cost
After choosing the root node S, we see that S,A and S,C are two edges with weight 7 and 8, respectively. We choose the edge S,A as it is lesser than the other.

Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We select the one which has the lowest cost and include it in the tree.

After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the edges again. However, we will choose only the least cost edge. In this case, C-3-D is the new edge, which is less than other edges' cost 8, 6, 4, etc.

After adding node D to the spanning tree, we now have two edges going out of it having the same cost, i.e. D-2-T and D-2-B. Thus, we can add either one. But the next step will again yield edge 2 as the least cost. Hence, we are showing a spanning tree with both edges included.

We may find that the output spanning tree of the same graph using two different algorithms is same.
Example
// C Code for Prim’s Spanning Tree Algorithm #include <stdio.h> #include <stdbool.h> #define MAX_VERTICES 100 #define INF 9999 int graph[MAX_VERTICES][MAX_VERTICES]; void primMST(int numVertices) { int parent[numVertices]; int key[numVertices]; bool mstSet[numVertices]; for (int i = 0; i < numVertices; i++) { key[i] = INF; mstSet[i] = false; } key[0] = 0; parent[0] = -1; for (int count = 0; count < numVertices - 1; count++) { int minKey = INF; int minIndex = 0; for (int X = 0; X < numVertices; X++) { if (mstSet[X] == false && key[X] < minKey) { minKey = key[X]; minIndex = X; } } mstSet[minIndex] = true; for (int X = 0; X < numVertices; X++) { if (graph[minIndex][X] && mstSet[X] == false && graph[minIndex][X] < key[X]) { parent[X] = minIndex; key[X] = graph[minIndex][X]; } } } printf("Edge \tWeight\n"); for (int i = 1; i < numVertices; i++) { printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]); } } int main() { int numVertices = 3; printf("Number of vertices: %d" , numVertices); int pgraph[3][3] = { {2, 3, 4}, {4, 5, 6}, {6, 7, 8} }; printf("\nAdjacency matrix: "); for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { printf("\npgraph[%d][%d] = %d", i, j, pgraph[i][j]); graph[i][j] = pgraph[i][j]; } } printf("\n"); primMST(numVertices); return 0; }
Output
Number of vertices: 3 Adjacency matrix: pgraph[0][0] = 2 pgraph[0][1] = 3 pgraph[0][2] = 4 pgraph[1][0] = 4 pgraph[1][1] = 5 pgraph[1][2] = 6 pgraph[2][0] = 6 pgraph[2][1] = 7 pgraph[2][2] = 8 Edge Weight 0 - 1 4 0 - 2 6
// C++ Code for Prim’s Spanning Tree Algorithm #include <iostream> #include <climits> #include <vector> using namespace std; #define MAX_VERTICES 100 #define INF INT_MAX vector<vector<int>> graph(MAX_VERTICES, vector<int>(MAX_VERTICES)); void primMST(int numVertices) { vector<int> parent(numVertices); vector<int> key(numVertices); vector<bool> mstSet(numVertices); for (int i = 0; i < numVertices; i++) { key[i] = INF; mstSet[i] = false; } key[0] = 0; parent[0] = -1; for (int count = 0; count < numVertices - 1; count++) { int minKey = INF; int minIndex = 0; for (int X = 0; X < numVertices; X++) { if (mstSet[X] == false && key[X] < minKey) { minKey = key[X]; minIndex = X; } } mstSet[minIndex] = true; for (int X = 0; X < numVertices; X++) { if (graph[minIndex][X] && mstSet[X] == false && graph[minIndex][X] < key[X]) { parent[X] = minIndex; key[X] = graph[minIndex][X]; } } } cout << "Edge \tWeight" << endl; for (int i = 1; i < numVertices; i++) { cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << endl; } } int main() { int numVertices = 3; cout << "Number of vertices: "<<numVertices<<endl; int pgraph[3][3] = { {2, 3, 4}, {4, 5, 6}, {6, 7, 8} }; cout << "Adjacency matrix:" << endl; for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { cout<<"pgraph["<<i<<"]"<<"["<<j<<"]"<<" = "<<pgraph[i][j]<<endl; graph[i][j] = pgraph[i][j]; } } primMST(numVertices); return 0; }
Output
Number of vertices: 3 Adjacency matrix: pgraph[0][0] = 2 pgraph[0][1] = 3 pgraph[0][2] = 4 pgraph[1][0] = 4 pgraph[1][1] = 5 pgraph[1][2] = 6 pgraph[2][0] = 6 pgraph[2][1] = 7 pgraph[2][2] = 8 Edge Weight 0 - 1 4 0 - 2 6
// Java code for Prim’s Spanning Tree Algorithm import java.util.Scanner; public class PrimSpanningTree { private static final int MAX_VERTICES = 100; private static final int INF = Integer.MAX_VALUE; private static int[][] graph = new int[MAX_VERTICES][MAX_VERTICES]; private static void primMST(int numVertices) { int[] parent = new int[numVertices]; int[] key = new int[numVertices]; boolean[] mstSet = new boolean[numVertices]; for (int i = 0; i < numVertices; i++) { key[i] = INF; mstSet[i] = false; } key[0] = 0; parent[0] = -1; for (int count = 0; count < numVertices - 1; count++) { int minKey = INF; int minIndex = 0; for (int X = 0; X < numVertices; X++) { if (!mstSet[X] && key[X] < minKey) { minKey = key[X]; minIndex = X; } } mstSet[minIndex] = true; for (int X = 0; X < numVertices; X++) { if (graph[minIndex][X] != 0 && !mstSet[X] && graph[minIndex][X] < key[X]) { parent[X] = minIndex; key[X] = graph[minIndex][X]; } } } System.out.println("Edge \tWeight"); for (int i = 1; i < numVertices; i++) { System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); } } public static void main(String[] args) { int numVertices = 3; System.out.print("Number of vertices are: " + numVertices + "\n"); int[][] pgraph = { {2, 3, 4}, {4, 5, 6}, {6, 7, 8} }; System.out.println("Adjacency matrix:"); for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { System.out.println("pgraph["+i+"]"+"["+j+"]" + " = " + pgraph[i][j]); graph[i][j] = pgraph[i][j]; } } primMST(numVertices); } }
Output
Number of vertices are: 3 Adjacency matrix: pgraph[0][0] = 2 pgraph[0][1] = 3 pgraph[0][2] = 4 pgraph[1][0] = 4 pgraph[1][1] = 5 pgraph[1][2] = 6 pgraph[2][0] = 6 pgraph[2][1] = 7 pgraph[2][2] = 8 Edge Weight 0 - 1 4 0 - 2 6
# Python Code for Prim’s Spanning Tree Algorithm MAX_VERTICES = 100 INF = float('inf') graph = [[0] * MAX_VERTICES for _ in range(MAX_VERTICES)] def primMST(numVertices): parent = [0] * numVertices key = [INF] * numVertices mstSet = [False] * numVertices key[0] = 0 parent[0] = -1 for count in range(numVertices - 1): minKey = INF minIndex = 0 for X in range(numVertices): if not mstSet[X] and key[X] < minKey: minKey = key[X] minIndex = X mstSet[minIndex] = True for X in range(numVertices): if graph[minIndex][ X] and not mstSet[X] and graph[minIndex][X] < key[X]: parent[X] = minIndex key[X] = graph[minIndex][X] print("Edge \tWeight") for i in range(1, numVertices): print(parent[i], "-", i, "\t", graph[i][parent[i]]) if __name__ == "__main__": numVertices = 3 print("Number of vertices are: ", numVertices) print("Adjacency matrix:") pgraph = [[2, 3, 4], [4, 5, 6], [6, 7, 8]] print(pgraph) graph = pgraph[:] primMST(numVertices)
Output
Number of vertices are: 3 Adjacency matrix: [[2, 3, 4], [4, 5, 6], [6, 7, 8]] Edge Weight 0 - 1 4 0 - 2 6