Given an undirected, connected and weighted graph, find Minimum Spanning Tree (MST) of the graph using Prim’s algorithm.

Input : Adjacency List representation of above graph Output : Edges in MST 0 - 1 1 - 2 2 - 3 3 - 4 2 - 5 5 - 6 6 - 7 2 - 8Note :There are two possible MSTs, the other MST includes edge 0-7 in place of 1-2.

We have discussed below Prim’s MST implementations.

- Prim’s Algorithm for Adjacency Matrix Representation (In C/C++ with time complexity O(v
^{2}) - Prim’s Algorithm for Adjacency List Representation (In C with Time Complexity O(ELogV))

The second implementation is time complexity wise better, but is really complex as we have implemented our own priority queue. STL provides priority_queue, but the provided priority queue doesn’t support decrease key operation. And in Prim’s algorithm, we need a priority queue and below operations on priority queue :

- ExtractMin : from all those vertices which have not yet been included in MST, we need to get vertex with minimum key value.
- DecreaseKey : After extracting vertex we need to update keys of its adjacent vertices, and if new key is smaller, then update that in data structure.

The algorithm discussed here can be modified so that decrease key is never required. The idea is, not to insert all vertices in priority queue, but only those which are not MST and have been visited through a vertex that has included in MST. We keep track of vertices included in MST in a separate boolean array inMST[].

1) Initialize keys of all vertices as infinite and parent of every vertex as -1. 2) Create an empty priority_queue pq. Every item of pq is a pair (weight, vertex). Weight (or key) is used used as first item of pair as first item is by default used to compare two pairs. 3) Initialize all vertices as not part of MST yet. We use boolean array inMST[] for this purpose. This array is required to make sure that an already considered vertex is not included in pq again. This is where Ptim's implementation differs from Dijkstra. In Dijkstr's algorithm, we didn't need this array as distances always increase. We require this array here because key value of a processed vertex may decrease if not checked. 4) Insert source vertex into pq and make its key as 0. 5) While either pq doesn't become empty a) Extract minimum key vertex from pq. Let the extracted vertex be u. b) Include u in MST using inMST[u] = true. c) Loop through all adjacent of u and do following for every vertex v. // If weight of edge (u,v) is smaller than // key of v and v is not already in MST If inMST[v] = false && key[v] > weight(u, v) (i) Update key of v, i.e., do key[v] = weight(u, v) (ii) Insert v into the pq (iv) parent[v] = u 6) Print MST edges using parent array.

Below is C++ implementation of above idea.

Output :

0 - 1 1 - 2 2 - 3 3 - 4 2 - 5 5 - 6 6 - 7 2 - 8

Time complexity : O(E Log V))