Improve
Suggest changes
414 Likes
Like
Report
Try it on GfG Practice
redirect icon

Prim’s algorithm is a Greedy algorithm like Kruskal's 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.

A group of edges that connects two sets of vertices in a graph is called Articulation Points (or Cut Vertices) 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).

Working of the Prim's Algorithm

Step 1: Determine an arbitrary vertex as the starting vertex of the MST. We pick 0 in the below diagram.
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. Since we consider only the edges that connect fringe vertices with the rest, we never get a cycle.
Step 6: Return the MST and exit


How to implement Prim's Algorithm?

Follow the given steps to utilize the Prim's Algorithm mentioned above for finding MST of a graph:

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:

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>
usingnamespacestd;
// A utility function to find the vertex with
// minimum key value, from the set of vertices
// not yet included in MST
intminKey(vector<int>&key,vector<bool>&mstSet){

// Initialize min value
intmin=INT_MAX,min_index;
for(intv=0;v<mstSet.size();v++)
if(mstSet[v]==false&&key[v]<min)
min=key[v],min_index=v;
returnmin_index;
}
// A utility function to print the
// constructed MST stored in parent[]
voidprintMST(vector<int>&parent,vector<vector<int>>&graph){
cout<<"Edge \tWeight\n";
for(inti=1;i<graph.size();i++)
cout<<parent[i]<<" - "<<i<<" \t"
<<graph[parent[i]][i]<<" \n";
}
// Function to construct and print MST for
// a graph represented using adjacency
// matrix representation
voidprimMST(vector<vector<int>>&graph){

intV=graph.size();

// Array to store constructed MST
vector<int>parent(V);
// Key values used to pick minimum weight edge in cut
vector<int>key(V);
// To represent set of vertices included in MST
vector<bool>mstSet(V);
// Initialize all keys as INFINITE
for(inti=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(intcount=0;count<V-1;count++){

// Pick the minimum key vertex from the
// set of vertices not yet included in MST
intu=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(intv=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
printMST(parent,graph);
}
// Driver's code
intmain(){
vector<vector<int>>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);
return0;
}
C
// 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
intminKey(intkey[],boolmstSet[])
{
// Initialize min value
intmin=INT_MAX,min_index;
for(intv=0;v<V;v++)
if(mstSet[v]==false&&key[v]<min)
min=key[v],min_index=v;
returnmin_index;
}
// A utility function to print the
// constructed MST stored in parent[]
intprintMST(intparent[],intgraph[V][V])
{
printf("Edge \tWeight\n");
for(inti=1;i<V;i++)
printf("%d - %d \t%d \n",parent[i],i,
graph[parent[i]][i]);
}
// Function to construct and print MST for
// a graph represented using adjacency
// matrix representation
voidprimMST(intgraph[V][V])
{
// Array to store constructed MST
intparent[V];
// Key values used to pick minimum weight edge in cut
intkey[V];
// To represent set of vertices included in MST
boolmstSet[V];
// Initialize all keys as INFINITE
for(inti=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(intcount=0;count<V-1;count++){

// Pick the minimum key vertex from the
// set of vertices not yet included in MST
intu=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(intv=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
printMST(parent,graph);
}
// Driver's code
intmain()
{
intgraph[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);
return0;
}
Java
// A Java program for Prim's Minimum Spanning Tree (MST)
// algorithm. The program is for adjacency matrix
// representation of the graph
importjava.io.*;
importjava.lang.*;
importjava.util.*;
class MST{
// A utility function to find the vertex with minimum
// key value, from the set of vertices not yet included
// in MST
intminKey(intkey[],BooleanmstSet[])
{
// Initialize min value
intmin=Integer.MAX_VALUE,min_index=-1;
for(intv=0;v<mstSet.length;v++)
if(mstSet[v]==false&&key[v]<min){
min=key[v];
min_index=v;
}
returnmin_index;
}
// A utility function to print the constructed MST
// stored in parent[]
voidprintMST(intparent[],intgraph[][])
{
System.out.println("Edge \tWeight");
for(inti=1;i<graph.length;i++)
System.out.println(parent[i]+" - "+i+"\t"
+graph[parent[i]][i]);
}
// Function to construct and print MST for a graph
// represented using adjacency matrix representation
voidprimMST(intgraph[][])
{
intV=graph.length;

// Array to store constructed MST
intparent[]=newint[V];
// Key values used to pick minimum weight edge in
// cut
intkey[]=newint[V];
// To represent set of vertices included in MST
BooleanmstSet[]=newBoolean[V];
// Initialize all keys as INFINITE
for(inti=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(intcount=0;count<V-1;count++){

// Pick the minimum key vertex from the set of
// vertices not yet included in MST
intu=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(intv=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);
}
publicstaticvoidmain(String[]args)
{
MSTt=newMST();
intgraph[][]=newint[][]{{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);
}
}
Python
# 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 
 # 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[parent[i]][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]:
 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#
// A C# program for Prim's Minimum Spanning Tree (MST)
// algorithm. The program is for adjacency matrix
// representation of the graph
usingSystem;
usingSystem.Collections.Generic;
classMST
{
// A utility function to find the vertex with minimum
// key value, from the set of vertices not yet included
// in MST
intMinKey(int[]key,bool[]mstSet)
{
// Initialize min value
intmin=int.MaxValue,minIndex=-1;
for(intv=0;v<mstSet.Length;v++)
if(!mstSet[v]&&key[v]<min)
{
min=key[v];
minIndex=v;
}
returnminIndex;
}
// A utility function to print the constructed MST
// stored in parent[]
voidPrintMST(int[]parent,int[,]graph)
{
Console.WriteLine("Edge \tWeight");
for(inti=1;i<graph.GetLength(0);i++)
Console.WriteLine(parent[i]+" - "+i+"\t"+graph[parent[i],i]);
}
// Function to construct and print MST for a graph
// represented using adjacency matrix representation
publicvoidPrimMST(int[,]graph)
{
intV=graph.GetLength(0);
// Array to store constructed MST
int[]parent=newint[V];
// Key values used to pick minimum weight edge in
// cut
int[]key=newint[V];
// To represent set of vertices included in MST
bool[]mstSet=newbool[V];
// Initialize all keys as INFINITE
for(inti=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
key[0]=0;
// First node is always root of MST
parent[0]=-1;
// The MST will have V vertices
for(intcount=0;count<V-1;count++)
{
// Pick the minimum key vertex from the set of
// vertices not yet included in MST
intu=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(intv=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]&&graph[u,v]<key[v])
{
parent[v]=u;
key[v]=graph[u,v];
}
}
// Print the constructed MST
PrintMST(parent,graph);
}
publicstaticvoidMain(string[]args)
{
MSTt=newMST();
int[,]graph=newint[,]{{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);
}
}
JavaScript
// Number of vertices in the graph 
letV=5;
// A utility function to find the vertex with 
// minimum key value, from the set of vertices 
// not yet included in MST 
functionminKey(key,mstSet){
// Initialize min value 
letmin=Number.MAX_VALUE,min_index=-1;
for(letv=0;v<V;v++)
if(!mstSet[v]&&key[v]<min){
min=key[v];
min_index=v;
}
returnmin_index;
}
// A utility function to print the 
// constructed MST stored in parent[] 
functionprintMST(parent,graph){
console.log("Edge Weight");
for(leti=1;i<V;i++)
console.log(parent[i]+" - "+i+" "+graph[parent[i]][i]);
}
// Function to construct and print MST for 
// a graph represented using adjacency matrix 
functionprimMST(graph){
// Array to store constructed MST 
letparent=newArray(V);

// Key values used to pick minimum weight edge in cut 
letkey=newArray(V);

// To represent set of vertices included in MST 
letmstSet=newArray(V);
// Initialize all keys as INFINITE 
for(leti=0;i<V;i++){
key[i]=Number.MAX_VALUE;
mstSet[i]=false;
}
// Always include first vertex in MST. 
key[0]=0;
parent[0]=-1;// First node is always root of MST 
// The MST will have V vertices 
for(letcount=0;count<V-1;count++){
// Pick the minimum key vertex from the set of vertices not yet included in MST 
letu=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. 
for(letv=0;v<V;v++){
// graph[u][v] is non-zero only for adjacent vertices of u 
// 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]&&graph[u][v]<key[v]){
parent[v]=u;
key[v]=graph[u][v];
}
}
}
// Print the constructed MST 
printMST(parent,graph);
}
// Driver code
letgraph=[
[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);

Output
Edge 	Weight
0 - 1 	2 
1 - 2 	3 
0 - 3 	6 
1 - 4 	5 

Time Complexity: O(V2), As, we are using adjacency matrix, if the input graph is represented using an adjacency list, then the time complexity of Prim's algorithm can be reduced to O((E+V) * logV) with the help of a binary heap.
Auxiliary Space: O(V)

Optimized Implementation using Adjacency List Representation (of Graph) and Priority Queue

  1. We transform the adjacency matrix into adjacency list using ArrayList<ArrayList<Integer>>. in Java, list of list in Python
    and array of vectors in C++.
  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.
C++
#include<bits/stdc++.h>
usingnamespacestd;
// Function to find sum of weights of edges of the Minimum Spanning Tree.
intspanningTree(intV,intE,vector<vector<int>>&edges){

// Create an adjacency list representation of the graph
vector<vector<int>>adj[V];

// Fill the adjacency list with edges and their weights
for(inti=0;i<E;i++){
intu=edges[i][0];
intv=edges[i][1];
intwt=edges[i][2];
adj[u].push_back({v,wt});
adj[v].push_back({u,wt});
}

// Create a priority queue to store edges with their weights
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;

// Create a visited array to keep track of visited vertices
vector<bool>visited(V,false);

// Variable to store the result (sum of edge weights)
intres=0;

// Start with vertex 0
pq.push({0,0});

// Perform Prim's algorithm to find the Minimum Spanning Tree
while(!pq.empty()){
autop=pq.top();
pq.pop();

intwt=p.first;// Weight of the edge
intu=p.second;// Vertex connected to the edge

if(visited[u]==true){
continue;// Skip if the vertex is already visited
}

res+=wt;// Add the edge weight to the result
visited[u]=true;// Mark the vertex as visited

// Explore the adjacent vertices
for(autov:adj[u]){
// v[0] represents the vertex and v[1] represents the edge weight
if(visited[v[0]]==false){
pq.push({v[1],v[0]});// Add the adjacent edge to the priority queue
}
}
}

returnres;// Return the sum of edge weights of the Minimum Spanning Tree
}
intmain(){
vector<vector<int>>graph={{0,1,5},
{1,2,3},
{0,2,1}};
cout<<spanningTree(3,3,graph)<<endl;
return0;
}
Java
// A Java program for Prim's Minimum Spanning Tree (MST)
// algorithm. The program is for adjacency list
// representation of the graph
importjava.io.*;
importjava.util.*;
// Class to form pair
class PairimplementsComparable<Pair>
{
intv;
intwt;
Pair(intv,intwt)
{
this.v=v;
this.wt=wt;
}
publicintcompareTo(Pairthat)
{
returnthis.wt-that.wt;
}
}
class GFG{
// Function of spanning tree
staticintspanningTree(intV,intE,intedges[][])
{
ArrayList<ArrayList<Pair>>adj=newArrayList<>();
for(inti=0;i<V;i++)
{
adj.add(newArrayList<Pair>());
}
for(inti=0;i<edges.length;i++)
{
intu=edges[i][0];
intv=edges[i][1];
intwt=edges[i][2];
adj.get(u).add(newPair(v,wt));
adj.get(v).add(newPair(u,wt));
}
PriorityQueue<Pair>pq=newPriorityQueue<Pair>();
pq.add(newPair(0,0));
int[]vis=newint[V];
ints=0;
while(!pq.isEmpty())
{
Pairnode=pq.poll();
intv=node.v;
intwt=node.wt;
if(vis[v]==1)
continue;

s+=wt;
vis[v]=1;
for(Pairit:adj.get(v))
{
if(vis[it.v]==0)
{
pq.add(newPair(it.v,it.wt));
}
}
}
returns;
}

// Driver code
publicstaticvoidmain(String[]args){
intgraph[][]=newint[][]{{0,1,5},
{1,2,3},
{0,2,1}};

// Function call
System.out.println(spanningTree(3,3,graph));
}
}
Python
import heapq
def tree(V, E, edges):
 # Create an adjacency list representation of the graph
 adj = [[] for _ in range(V)]
 # Fill the adjacency list with edges and their weights
 for i in range(E):
 u, v, wt = edges[i]
 adj[u].append((v, wt))
 adj[v].append((u, wt))
 # Create a priority queue to store edges with their weights
 pq = []
 # Create a visited array to keep track of visited vertices
 visited = [False] * V
 # Variable to store the result (sum of edge weights)
 res = 0
 # Start with vertex 0
 heapq.heappush(pq, (0, 0))
 # Perform Prim's algorithm to find the Minimum Spanning Tree
 while pq:
 wt, u = heapq.heappop(pq)
 if visited[u]:
 continue 
 # Skip if the vertex is already visited
 res += wt 
 # Add the edge weight to the result
 visited[u] = True 
 # Mark the vertex as visited
 # Explore the adjacent vertices
 for v, weight in adj[u]:
 if not visited[v]:
 heapq.heappush(pq, (weight, v)) 
 # Add the adjacent edge to the priority queue
 return res 
 # Return the sum of edge weights of the Minimum Spanning Tree
if __name__ == "__main__":
 graph = [[0, 1, 5],
 [1, 2, 3],
 [0, 2, 1]]
 # Function call
 print(tree(3, 3, graph))
C#
usingSystem;
usingSystem.Collections.Generic;
publicclassMinimumSpanningTree
{
// Function to find sum of weights of edges of the Minimum Spanning Tree.
publicstaticintSpanningTree(intV,intE,int[,]edges)
{
// Create an adjacency list representation of the graph
List<List<int[]>>adj=newList<List<int[]>>();
for(inti=0;i<V;i++)
{
adj.Add(newList<int[]>());
}
// Fill the adjacency list with edges and their weights
for(inti=0;i<E;i++)
{
intu=edges[i,0];
intv=edges[i,1];
intwt=edges[i,2];
adj[u].Add(newint[]{v,wt});
adj[v].Add(newint[]{u,wt});
}
// Create a priority queue to store edges with their weights
PriorityQueue<(int,int)>pq=newPriorityQueue<(int,int)>();
// Create a visited array to keep track of visited vertices
bool[]visited=newbool[V];
// Variable to store the result (sum of edge weights)
intres=0;
// Start with vertex 0
pq.Enqueue((0,0));
// Perform Prim's algorithm to find the Minimum Spanning Tree
while(pq.Count>0)
{
varp=pq.Dequeue();
intwt=p.Item1;// Weight of the edge
intu=p.Item2;// Vertex connected to the edge
if(visited[u])
{
continue;// Skip if the vertex is already visited
}
res+=wt;// Add the edge weight to the result
visited[u]=true;// Mark the vertex as visited
// Explore the adjacent vertices
foreach(varvinadj[u])
{
// v[0] represents the vertex and v[1] represents the edge weight
if(!visited[v[0]])
{
pq.Enqueue((v[1],v[0]));// Add the adjacent edge to the priority queue
}
}
}
returnres;// Return the sum of edge weights of the Minimum Spanning Tree
}
publicstaticvoidMain()
{
int[,]graph={{0,1,5},{1,2,3},{0,2,1}};
// Function call
Console.WriteLine(SpanningTree(3,3,graph));
}
}
// PriorityQueue implementation for C#
publicclassPriorityQueue<T>whereT:IComparable<T>
{
privateList<T>heap=newList<T>();
publicintCount=>heap.Count;
publicvoidEnqueue(Titem)
{
heap.Add(item);
inti=heap.Count-1;
while(i>0)
{
intparent=(i-1)/2;
if(heap[parent].CompareTo(heap[i])<=0)
break;
Swap(parent,i);
i=parent;
}
}
publicTDequeue()
{
intlastIndex=heap.Count-1;
TfrontItem=heap[0];
heap[0]=heap[lastIndex];
heap.RemoveAt(lastIndex);
--lastIndex;
intparent=0;
while(true)
{
intleftChild=parent*2+1;
if(leftChild>lastIndex)
break;
intrightChild=leftChild+1;
if(rightChild<=lastIndex&&heap[leftChild].CompareTo(heap[rightChild])>0)
leftChild=rightChild;
if(heap[parent].CompareTo(heap[leftChild])<=0)
break;
Swap(parent,leftChild);
parent=leftChild;
}
returnfrontItem;
}
privatevoidSwap(inti,intj)
{
Ttemp=heap[i];
heap[i]=heap[j];
heap[j]=temp;
}
}
JavaScript
classPriorityQueue{
constructor(){
this.heap=[];
}
enqueue(value){
this.heap.push(value);
leti=this.heap.length-1;
while(i>0){
letj=Math.floor((i-1)/2);
if(this.heap[i][0]>=this.heap[j][0]){
break;
}
[this.heap[i],this.heap[j]]=[this.heap[j],this.heap[i]];
i=j;
}
}
dequeue(){
if(this.heap.length===0){
thrownewError("Queue is empty");
}
leti=this.heap.length-1;
constresult=this.heap[0];
this.heap[0]=this.heap[i];
this.heap.pop();
i--;
letj=0;
while(true){
constleft=j*2+1;
if(left>i){
break;
}
constright=left+1;
letk=left;
if(right<=i&&this.heap[right][0]<this.heap[left][0]){
k=right;
}
if(this.heap[j][0]<=this.heap[k][0]){
break;
}
[this.heap[j],this.heap[k]]=[this.heap[k],this.heap[j]];
j=k;
}
returnresult;
}
getcount(){
returnthis.heap.length;
}
}
functionspanningTree(V,E,edges){
// Create an adjacency list representation of the graph
constadj=newArray(V).fill(null).map(()=>[]);
// Fill the adjacency list with edges and their weights
for(leti=0;i<E;i++){
const[u,v,wt]=edges[i];
adj[u].push([v,wt]);
adj[v].push([u,wt]);
}
// Create a priority queue to store edges with their weights
constpq=newPriorityQueue();
// Create a visited array to keep track of visited vertices
constvisited=newArray(V).fill(false);
// Variable to store the result (sum of edge weights)
letres=0;
// Start with vertex 0
pq.enqueue([0,0]);
// Perform Prim's algorithm to find the Minimum Spanning Tree
while(pq.count>0){
constp=pq.dequeue();
constwt=p[0];// Weight of the edge
constu=p[1];// Vertex connected to the edge
if(visited[u]){
continue;// Skip if the vertex is already visited
}
res+=wt;// Add the edge weight to the result
visited[u]=true;// Mark the vertex as visited
// Explore the adjacent vertices
for(constvofadj[u]){
// v[0] represents the vertex and v[1] represents the edge weight
if(!visited[v[0]]){
pq.enqueue([v[1],v[0]]);// Add the adjacent edge to the priority queue
}
}
}
returnres;// Return the sum of edge weights of the Minimum Spanning Tree
}
// Example usage
constgraph=[[0,1,5],[1,2,3],[0,2,1]];
// Function call
console.log(spanningTree(3,3,graph));

Output
4

Time Complexity: O((E+V)*log(V)) where V is the number of vertex and E is the number of edges
Auxiliary Space: O(E+V) where V is the number of vertex and E is the number of edges

Advantages and Disadvantages of Prim's algorithm

Advantages:

Disadvantages:

Also Check:

Problems based on Minimum Spanning Tree


[フレーム]
Prim's Algorithm/Minimum Spanning Tree
Visit Course explore course icon
Video Thumbnail

Prim's Algorithm/Minimum Spanning Tree

Video Thumbnail

Implementation of Prims Algorithm

Improve
Improve
Article Tags :
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

AltStyle によって変換されたページ (->オリジナル) /