0% found this document useful (0 votes)
861 views28 pages

Prim's Algorithm For Minimum Spanning Tree (MST) - GeeksforGeeks

It is about minimum spanning algorithm.

Uploaded by

Abeyu Assefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
861 views28 pages

Prim's Algorithm For Minimum Spanning Tree (MST) - GeeksforGeeks

It is about minimum spanning algorithm.

Uploaded by

Abeyu Assefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks

Prim’s Algorithm for Minimum Spanning Tree (MST)

Read Discuss(50+) Courses Practice Video

Introduction to Prim’s algorithm:


We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s algorithm,
Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node and
moves through several adjacent nodes, in order to explore all of the connected edges along the
way.

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).

How does Prim’s Algorithm Work?


The working of Prim’s algorithm can be described by using the following steps:

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

Step 1: Determine an arbitrary vertex as the starting vertex of the MST.


Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as
fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit

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

Minimum Spanning Tree Solve Problem


Greedy Graph +2 more Flipkart Amazon +3 more
Submission count: 80.4K

Illustration of Prim’s Algorithm:

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.

0 is selected as 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

1 is added to the MST

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

7 is added in the MST

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).

6 is added in the MST

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.

Include vertex 5 in the MST

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.

Include 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

Add vertex 8 in the MST

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.

Include vertex 3 in 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

Include vertex 4 in the MST

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.

The structure of the MST formed using the above method

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

How to implement Prim’s Algorithm?

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.

Below is the implementation of the approach:

// A C program for Prim's Minimum


// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 5

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

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

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

// A utility function to print the


// constructed MST stored in parent[]
int printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i,
graph[i][parent[i]]);
}

// 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];
// Key values used to pick minimum weight edge in cut
int key[V];
// To represent set of vertices included in MST
bool mstSet[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the


// set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 10/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for vertices
// not yet included in MST Update the key only
// if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
&& graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST


printMST(parent, graph);
}

// 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 } };

// Print the solution


primMST(graph);

return 0;
}

C++

// A C++ program for Prim's Minimum


// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph

#include <bits/stdc++.h>
using namespace std;

// Number of vertices in the graph


#define V 5

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

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

// A utility function to print the


// constructed MST stored in parent[]
void printMST(int parent[], int graph[V][V])
{
cout << "Edge \tWeight\n";
for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << " \t"
<< graph[i][parent[i]] << " \n";
}

// 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];

// Key values used to pick minimum weight edge in cut


int key[V];

// To represent set of vertices included in MST


bool mstSet[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the


// set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for vertices
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 12/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks

// not yet included in MST Update the key only


// if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
&& graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// Print the constructed MST


printMST(parent, graph);
}

// 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 } };

// Print the solution


primMST(graph);

return 0;
}

// This code is contributed by rathbhupendra

Java

// A Java program for Prim's Minimum Spanning Tree (MST)


// algorithm. The program is for adjacency matrix
// representation of the graph

import java.io.*;
import java.lang.*;
import java.util.*;

class MST {

// Number of vertices in the graph


private static final int V = 5;

// A utility function to find the vertex with minimum


// key value, from the set of vertices not yet included
// in MST
int minKey(int key[], Boolean mstSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min) {
min = key[v];

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;
}

// A utility function to print the constructed MST


// stored in parent[]
void printMST(int parent[], int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + "\t"
+ graph[i][parent[i]]);
}

// Function to construct and print MST for a graph


// represented using adjacency matrix representation
void primMST(int graph[][])
{
// Array to store constructed MST
int parent[] = new int[V];

// Key values used to pick minimum weight edge in


// cut
int key[] = new int[V];

// To represent set of vertices included in MST


Boolean mstSet[] = new Boolean[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is
// picked as first vertex
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the set of


// vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of the


// adjacent vertices of the picked vertex.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 14/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks

// Consider only those vertices which are not


// yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for
// vertices not yet included in MST Update
// the key only if graph[u][v] is smaller
// than key[v]
if (graph[u][v] != 0 && mstSet[v] == false
&& graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}

// Print the constructed MST


printMST(parent, graph);
}

public static void main(String[] args)


{
MST t = new MST();
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 } };

// Print the solution


t.primMST(graph);
}
}

// This code is contributed by Aakash Hasija

Python3

# A Python3 program for


# Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix
# representation of the graph

# Library for INT_MAX


import sys

class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

# A utility function to print

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

# the constructed MST stored in parent[]


def printMST(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minKey(self, key, mstSet):

# Initialize min value


min = sys.maxsize

for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v

return min_index

# Function to construct and print MST for a graph


# represented using adjacency matrix representation
def primMST(self):

# Key values used to pick minimum weight edge in cut


key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V

parent[0] = -1 # First node is always the root of

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minKey(key, mstSet)

# Put the minimum distance vertex in


# the shortest path tree
mstSet[u] = True

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):

# graph[u][v] is non zero only for adjacent vertices of m


# mstSet[v] is false for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]
if self.graph[u][v] > 0 and mstSet[v] == False \
and key[v] > self.graph[u][v]:
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 16/28
6/14/23, 4:08 PM Prim’s Algorithm for Minimum Spanning Tree (MST) - GeeksforGeeks

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()

# Contributed by Divyanshu Mehta

C#

// A C# program for Prim's Minimum


// Spanning Tree (MST) algorithm.
// The program is for adjacency
// matrix representation of the graph

using System;
class MST {

// Number of vertices in the graph


static int V = 5;

// A utility function to find


// the vertex with minimum key
// value, from the set of vertices
// not yet included in MST
static int minKey(int[] key, bool[] mstSet)
{
// Initialize min value
int min = int.MaxValue, min_index = -1;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}

return min_index;
}

// A utility function to print


// the constructed MST stored in parent[]
static void printMST(int[] parent, int[, ] graph)

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]]);
}

// Function to construct and


// print MST for a graph represented
// using adjacency matrix representation
static void primMST(int[, ] graph)
{
// Array to store constructed MST
int[] parent = new int[V];

// Key values used to pick


// minimum weight edge in cut
int[] key = new int[V];

// To represent set of vertices


// included in MST
bool[] mstSet = new bool[V];

// Initialize all keys


// as INFINITE
for (int i = 0; i < V; i++) {
key[i] = int.MaxValue;
mstSet[i] = false;
}

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is
// picked as first vertex
// First node is always root of MST
key[0] = 0;
parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex


// from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex


// to the MST Set
mstSet[u] = true;

// Update key value and parent


// index of the adjacent vertices
// of the picked vertex. Consider
// only those vertices which are
// not yet included in MST
for (int v = 0; v < V; v++)

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

// graph[u][v] is non zero only


// for adjacent vertices of m
// mstSet[v] is false for vertices
// not yet included in MST Update
// the key only if graph[u][v] is
// smaller than key[v]
if (graph[u, v] != 0 && mstSet[v] == false
&& graph[u, v] < key[v]) {
parent[v] = u;
key[v] = graph[u, v];
}
}

// Print the constructed MST


printMST(parent, graph);
}

// 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 } };

// Print the solution


primMST(graph);
}
}

// This code is contributed by anuj_67.

Javascript

// Number of vertices in the graph


let V = 5;

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
function minKey(key, mstSet)
{
// Initialize min value
let min = Number.MAX_VALUE, min_index;

for (let v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

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

// A utility function to print the


// constructed MST stored in parent[]
function printMST(parent, graph)
{
document.write("Edge Weight" + "<br>");
for (let i = 1; i < V; i++)
document.write(parent[i] + " - " + i + " " + graph[i][parent[i]] + "<br>");
}

// Function to construct and print MST for


// a graph represented using adjacency
// matrix representation
function primMST(graph)
{
// Array to store constructed MST
let parent = [];

// Key values used to pick minimum weight edge in cut


let key = [];

// To represent set of vertices included in MST


let mstSet = [];

// Initialize all keys as INFINITE


for (let i = 0; i < V; i++)
key[i] = Number.MAX_VALUE, mstSet[i] = false;

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is picked as first vertex.
key[0] = 0;
parent[0] = -1; // First node is always root of MST

// The MST will have V vertices


for (let count = 0; count < V - 1; count++)
{
// Pick the minimum key vertex from the
// set of vertices not yet included in MST
let u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (let v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent vertices of m


// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST


https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 20/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 ] ];

// Print the solution


primMST(graph);

// This code is contributed by Dharanendra L V.

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)

Other Implementations of Prim’s Algorithm:

Given below are some other implementations of Prim’s Algorithm

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.

OPTIMIZED APPROACH OF 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

1. We transform the adjacency matrix into adjacency list using


ArrayList<ArrayList<Integer>>.
2. Then we create a Pair class to store the vertex and its weight .
3. We sort the list on the basis of lowest weight.
4. We create priority queue and push the first vertex and its weight in the queue
5. Then we just traverse through its edges and store the least weight in a variable called
ans.
6. At last after all the vertex we return the ans.

Implementation

Java

// A Java program for Prim's Minimum Spanning Tree (MST)


// algorithm. The program is for adjacency list
// representation of the graph

import java.io.*;
import java.util.*;

// Class to form pair


class Pair implements Comparable<Pair>
{
int v;
int wt;
Pair(int v,int wt)
{
this.v=v;
this.wt=wt;
}
public int compareTo(Pair that)
{
return this.wt-that.wt;
}
}

class GFG {

// Function of spanning tree


static int spanningTree(int V, int E, int edges[][])
{
ArrayList<ArrayList<Pair>> adj=new ArrayList<>();
for(int i=0;i<V;i++)
{
adj.add(new ArrayList<Pair>());
}
for(int i=0;i<edges.length;i++)
{

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

Time Complexity: O(E*log(E)) where E is the number of edges


Auxiliary Space: O(V^2) where V is the number of vertex

Prim’s algorithm for finding the minimum spanning tree (MST):

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:

1. Prim’s algorithm is guaranteed to find the MST in a connected, weighted graph.


2. It has a time complexity of O(E log V) using a binary heap or Fibonacci heap, where E is the
number of edges and V is the number of vertices.
3. It is a relatively simple algorithm to understand and implement compared to some other MST
algorithms.

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.

Last Updated : 19 May, 2023 370

Similar Reads

1. Kruskal’s Minimum Spanning Tree (MST) Algorithm

2. Difference between Prim's and Kruskal's algorithm for MST

3. Why Prim’s and Kruskal's MST algorithm fails for Directed Graph?

4. Maximum Spanning Tree using Prim’s Algorithm

5. Properties of Minimum Spanning Tree (MST)

6. What is Minimum Spanning Tree (MST)

7. Prim’s MST for Adjacency List Representation | Greedy Algo-6

8. Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)

9. Boruvka's algorithm for Minimum Spanning Tree

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

10. Reverse Delete Algorithm for Minimum Spanning Tree

Related Tutorials

1. Learn Data Structures with Javascript | DSA Tutorial

2. Introduction to Max-Heap – Data Structure and Algorithm Tutorials

3. Introduction to Set – Data Structure and Algorithm Tutorials

4. Introduction to Map – Data Structure and Algorithm Tutorials

5. What is Dijkstra’s Algorithm? | Introduction to Dijkstra's Shortest Path Algorithm

Previous Next

Article Contributed By :

GeeksforGeeks

Vote for difficulty


Current difficulty : Medium

Easy Normal Medium Hard Expert

Improved By : vt_m, AnkurKarmakar, udkumar249, GlitchFinder, rathbhupendra, POuryaKordi, AliZaidi1,


user_9781, varun_b_g, dharanendralv23, arorakashish0911, geeky01adarsh, simmytarika5,
amartyaghoshgfg, animeshdey, kushalpareek, mitalibhola94, kumargaurav97520, janardansthox,
avinashrat55252, anikettchpiow, singhraunak1000

Article Tags : Amazon, Cisco, Minimum Spanning Tree, Prim's Algorithm.MST, Samsung, DSA, Graph, Greedy

Practice Tags : Amazon, Cisco, Samsung, Graph, Greedy

Improve Article Report Issue

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

[email protected]

Company Explore

About Us Job Fair For Students

Legal POTD: Revamped

Careers Python Backend LIVE

In Media Android App Development

Contact Us DevOps LIVE

Advertise with us DSA in JavaScript

Languages Data Structures


Python Array

Java String

C++ Linked List

PHP Stack

GoLang Queue

SQL Tree

R Language Graph

Android Tutorial

Algorithms Web Development


Sorting HTML

Searching CSS

Greedy JavaScript

Dynamic Programming Bootstrap

Pattern Searching ReactJS

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

Computer Science Python


GATE CS Notes Python Programming Examples

Operating Systems Django Tutorial

Computer Network Python Projects

Database Management System Python Tkinter

Software Engineering OpenCV Python Tutorial

Digital Logic Design Python Interview Question

Engineering Maths

Data Science & ML DevOps


Data Science With Python Git

Data Science For Beginner AWS

Machine Learning Tutorial Docker

Maths For Machine Learning Kubernetes

Pandas Tutorial Azure

NumPy Tutorial GCP

NLP Tutorial

Deep Learning Tutorial

Competitive Programming System Design


Top DSA for CP What is System Design

Top 50 Tree Problems Monolithic and Distributed SD

Top 50 Graph Problems Scalability in SD

Top 50 Array Problems Databases in SD

Top 50 String Problems High Level Design or HLD

Top 50 DP Problems Low Level Design or LLD

Top 15 Websites for CP Top SD Interview Questions

Interview Corner GfG School


Company Preparation CBSE Notes for Class 8

Preparation for SDE CBSE Notes for Class 9

Company Interview Corner CBSE Notes for Class 10

Experienced Interview CBSE Notes for Class 11

Internship Interview CBSE Notes for Class 12

Competitive Programming English Grammar

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

Business Studies Geography Notes

Microeconomics History Notes

Macroeconomics Science and Technology Notes

Statistics for Economics Economics Notes

Indian Economic Development Important Topics in Ethics

Income Tax UPSC Previous Year Papers

Management

SSC/ BANKING Write & Earn


SSC CGL Syllabus Write an Article

SBI PO Syllabus Improve an Article

SBI Clerk Syllabus Pick Topics to Write

IBPS PO Syllabus Write Interview Experience

IBPS Clerk Syllabus Internships

Aptitude Questions Video Internship

SSC CGL Practice Papers

@geeksforgeeks , Some rights reserved

https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 28/28

You might also like