Open In App

Minimum Spanning Tree using Priority Queue and Array List

Last Updated : 05 Nov, 2021
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given a bi-directed weighted (positive) graph without self-loops, the task is to generate the minimum spanning tree of the graph.
Examples: 
 

Input: N = 9, E = 14, edges = {{0, 1, 4}, {0, 7, 8}, {1, 2, 8}, {1, 7, 11}, {2, 3, 7}, {2, 8, 2}, {2, 5, 4}, {3, 4, 9}, {3, 5, 14}, {4, 5, 10}, {5, 6, 2}, {6, 7, 1}, {6, 8, 6}, {7, 8, 7}} 
Output: 
((A, B), Cost) 
((6, 7), 1) 
((6, 5), 2) 
((1, 0), 4) 
((2, 3), 7) 
((5, 2), 4) 
((3, 4), 9) 
((2, 1), 8) 
((2, 8), 2) 
 

Example


An undirected graph consisting of all the vertices V and (V-1) edges has been generated
Input: N = 6, E = 14, edges = {{0, 2, 103}, {0, 1, 158}, {0, 2, 2}, {0, 5, 17}, {1, 3, 42}, {2, 4, 187}, {3, 0, 14}, {3, 2, 158}, {3, 5, 106}, {3, 4, 95}, {5, 1, 144}, {5, 2, 194}, {5, 3, 118}, {5, 3, 58}} 
Output: 
((A, B), Cost) 
((0, 2), 2) 
((0, 3), 14) 
((0, 5), 17) 
((3, 1), 42) 
((3, 4), 95) 
 


 


Approach 
 

  • First, the edge having minimum cost/weight is found in the given graph.
  • The two initial vertices (vertex A, B of minimum cost edge) is added to visited/added set.
  • Now, all the connected edges with newly added vertex are added to priority queue.
  • The least cost vertex (add all the connected edges of pop vertex to priority queue) is popped from the priority queue and repeat until number of edges is equal to vertices-1.
  • By using priority queue time complexity will be reduced to (O(E log V)) where E is the number of edges and V is the number of vertices.
  • Pair class is also used to store the weights.


Below is the implementation of the above approach:
 


Output: 
((A, B), Cost)
((6, 7), 1)
((6, 5), 2)
((1, 0), 4)
((2, 3), 7)
((5, 2), 4)
((3, 4), 9)
((2, 1), 8)
((2, 8), 2)

 

Next Article

Similar Reads