VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-spanning-tree-using-prims-algorithm/

⇱ Maximum Spanning Tree using Prim’s Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Spanning Tree using Prim’s Algorithm

Last Updated : 23 Jul, 2025

Given undirected weighted graph G, the task is to find the Maximum Spanning Tree of the Graph using Prim's Algorithm

Prims algorithm is a Greedy algorithm which can be used to find the Minimum Spanning Tree (MST) as well as the Maximum Spanning Tree of a Graph.

Examples:

Input: 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}}
Output:
The total weight of the Maximum Spanning tree is 30.
Edges   Weight
3 - 1        8
4 - 2        7
0 - 3        6
3 - 4        9
Explanation:
Choosing other edges won't result in maximum spanning tree.

👁 Image

Maximum Spanning Tree:

Given an undirected weighted graph, a maximum spanning tree is a spanning tree having maximum weight. It can be easily computed using Prim’s algorithm. The goal here is to find the spanning tree with the maximum weight out of all possible spanning trees.

Prim’s Algorithm:

Prim’s algorithm is a greedy algorithm, which works on the idea that a spanning tree must have all its vertices connected. The algorithm works by building the tree one vertex at a time, from an arbitrary starting vertex, and adding the most expensive possible connection from the tree to another vertex, which will give us the Maximum Spanning Tree (MST).

Follow the steps below to solve the problem:

  • Initialize a visited array of boolean datatype, to keep track of vertices visited so far. Initialize all the values with false.
  • Initialize an array weights[], representing the maximum weight to connect that vertex. Initialize all the values with some minimum value.
  • Initialize an array parent[], to keep track of the maximum spanning tree.
  • Assign some large value, as the weight of the first vertex and parent as -1, so that it is picked first and has no parent.
  • From all the unvisited vertices, pick a vertex v having a maximum weight and mark it as visited.
  • Update the weights of all the unvisited adjacent vertices of v. To update the weights, iterate through all the unvisited neighbors of v. For every adjacent vertex x, if the weight of the edge between v and x is greater than the previous value of v, update the value of v with that weight.

Below is the implementation of the above algorithm:

 
 


Output: 
Weight of the maximum Spanning-tree 30

Edges Weight
3 - 1 8 
4 - 2 7 
0 - 3 6 
3 - 4 9

 


 

Time Complexity: O(V2) where V is the number of nodes in the graph.
Auxiliary Space: O(V2)


 

Comment