Prim's Algorithm For Minimum Spanning Tree (MST) - GeeksforGeeks
Prim's Algorithm For Minimum Spanning Tree (MST) - GeeksforGeeks
The algorithm starts with an empty spanning tree. The idea is to maintain two sets of
vertices. The first set contains the vertices already included in the MST, and the other set
contains the vertices not yet included. At every step, it considers all the edges that connect
the two sets and picks the minimum weight edge from these edges. After picking the edge,
it moves the other endpoint of the edge to the set containing MST.
A group of edges that connects two sets of vertices in a graph is called cut in graph theory. So, at
every step of Prim’s algorithm, find a cut, pick the minimum weight edge from the cut, and include
this vertex in MST Set (the set that contains already included vertices).
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 1/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Note: For determining a cycle, we can divide the vertices into two sets [one set contains the
vertices included in MST and the other contains the fringe vertices.]
Recommended Problem
Consider the following graph as an example for which we need to find the Minimum
Spanning Tree (MST).
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 2/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Example of a graph
Step 1: Firstly, we select an arbitrary vertex that acts as the starting vertex of the Minimum
Spanning Tree. Here we have selected vertex 0 as the starting vertex.
Step 2: All the edges connecting the incomplete MST and other vertices are the edges {0, 1}
and {0, 7}. Between these two the edge with minimum weight is {0, 1}. So include the edge
and vertex 1 in the MST.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 3/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Step 3: The edges connecting the incomplete MST to other vertices are {0, 7}, {1, 7} and {1,
2}. Among these edges the minimum weight is 8 which is of the edges {0, 7} and {1, 2}. Let
us here include the edge {0, 7} and the vertex 7 in the MST. [We could have also included
edge {1, 2} and vertex 2 in the MST].
DSA Data Structures Algorithms Array Strings Linked List Stack Queue Tree Graph Searching Sortin
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 4/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Step 4: The edges that connect the incomplete MST with the fringe vertices are {1, 2}, {7, 6}
and {7, 8}. Add the edge {7, 6} and the vertex 6 in the MST as it has the least weight (i.e., 1).
Step 5: The connecting edges now are {7, 8}, {1, 2}, {6, 8} and {6, 5}. Include edge {6, 5} and
vertex 5 in the MST as the edge has the minimum weight (i.e., 2) among them.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 5/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Step 6: Among the current connecting edges, the edge {5, 2} has the minimum weight. So
include that edge and the vertex 2 in the MST.
Step 7: The connecting edges between the incomplete MST and the other edges are {2, 8},
{2, 3}, {5, 3} and {5, 4}. The edge with minimum weight is edge {2, 8} which has weight 2.
So include this edge and the vertex 8 in the MST.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 6/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Step 8: See here that the edges {7, 8} and {2, 3} both have same weight which are
minimum. But 7 is already part of MST. So we will consider the edge {2, 3} and include that
edge and vertex 3 in the MST.
Step 9: Only the vertex 4 remains to be included. The minimum weighted edge from the
incomplete MST to 4 is {3, 4}.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 7/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
The final structure of the MST is as follows and the weight of the edges of the MST is (4 + 8
+ 1 + 2 + 4 + 2 + 7 + 9) = 37.
Note: If we had selected the edge {1, 2} in the third step then the MST would look like the
following.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 8/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Structure of the alternate MST if we had selected edge {1, 2} in the MST
Follow the given steps to utilize the Prim’s Algorithm mentioned above for finding MST of a
graph:
Create a set mstSet that keeps track of vertices already included in MST.
Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign
the key value as 0 for the first vertex so that it is picked first.
While mstSet doesn’t include all vertices
Pick a vertex u that is not there in mstSet and has a minimum key value.
Include u in the mstSet.
Update the key value of all adjacent vertices of u. To update the key values, iterate through
all adjacent vertices.
For every adjacent vertex v, if the weight of edge u-v is less than the previous key value
of v, update the key value as the weight of u-v.
The idea of using key values is to pick the minimum weight edge from the cut. The key values are
used only for vertices that are not yet included in MST, the key value for these vertices indicates
the minimum weight edges connecting them to the set of vertices included in MST.
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 9/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
return min_index;
}
// Driver's code
int main()
{
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 } };
return 0;
}
C++
#include <bits/stdc++.h>
using namespace std;
return min_index;
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 11/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
// Driver's code
int main()
{
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 } };
return 0;
}
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class MST {
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 13/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
min_index = v;
}
return min_index;
}
Python3
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 15/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
# Driver's code
if __name__ == '__main__':
g = Graph(5)
g.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]]
g.primMST()
C#
using System;
class MST {
return min_index;
}
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 17/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
{
Console.WriteLine("Edge \tWeight");
for (int i = 1; i < V; i++)
Console.WriteLine(parent[i] + " - " + i + "\t"
+ graph[i, parent[i]]);
}
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 18/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
// Driver's Code
public static void Main()
{
int[, ] graph = new int[, ] { { 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 } };
Javascript
return min_index;
}
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 19/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
printMST(parent, graph);
}
// Driver code
let 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 ] ];
Output
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
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)
Prim’s Algorithm for Adjacency Matrix Representation – In this article we have discussed the
method of implementing Prim’s Algorithm if the graph is represented by an adjacency matrix.
Prim’s Algorithm for Adjacency List Representation – In this article Prim’s Algorithm
implementation is described for graphs represented by an adjacency list.
Prim’s Algorithm using Priority Queue: In this article, we have discussed a time-efficient
approach to implement Prim’s algorithm.
Intuition
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 21/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Implementation
Java
import java.io.*;
import java.util.*;
class GFG {
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 22/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
int u=edges[i][0];
int v=edges[i][1];
int wt=edges[i][2];
adj.get(u).add(new Pair(v,wt));
adj.get(v).add(new Pair(u,wt));
}
PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
pq.add(new Pair(0,0));
int[] vis=new int[V];
int s=0;
while(!pq.isEmpty())
{
Pair node=pq.poll();
int v=node.v;
int wt=node.wt;
if(vis[v]==1)
continue;
s+=wt;
vis[v]=1;
for(Pair it:adj.get(v))
{
if(vis[it.v]==0)
{
pq.add(new Pair(it.v,it.wt));
}
}
}
return s;
}
// Driver code
public static void main (String[] args) {
int graph[][] = new int[][] {{0,1,5},
{1,2,3},
{0,2,1}};
// Function call
System.out.println(spanningTree(3,3,graph));
}
}
Output
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 23/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Advantages:
Disadvantages:
1. Like Kruskal’s algorithm, Prim’s algorithm can be slow on dense graphs with many edges, as it
requires iterating over all edges at least once.
2. Prim’s algorithm relies on a priority queue, which can take up extra memory and slow down the
algorithm on very large graphs.
3. The choice of starting node can affect the MST output, which may not be desirable in some
applications.
Similar Reads
3. Why Prim’s and Kruskal's MST algorithm fails for Directed Graph?
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 24/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Related Tutorials
Previous Next
Article Contributed By :
GeeksforGeeks
Article Tags : Amazon, Cisco, Minimum Spanning Tree, Prim's Algorithm.MST, Samsung, DSA, Graph, Greedy
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 25/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
A-143, 9th Floor, Sovereign Corporate
Tower, Sector-136, Noida, Uttar Pradesh -
201305
Company Explore
Java String
PHP Stack
GoLang Queue
SQL Tree
R Language Graph
Android Tutorial
Searching CSS
Greedy JavaScript
Recursion AngularJS
Backtracking NodeJS
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 26/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Engineering Maths
NLP Tutorial
Aptitude
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 27/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks
Commerce UPSC
Accountancy Polity Notes
Management
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 28/28