![]() |
VOOZH | about |
Given an undirected, connected and weighted graph, find Minimum Spanning Tree (MST) of the graph using Kruskal's algorithm.
Input : Graph as an array of edges Output : Edges of MST are 6 - 7 2 - 8 5 - 6 0 - 1 2 - 5 2 - 3 0 - 7 3 - 4 Weight of MST is 37 Note : There are two possible MSTs, the other MST includes edge 1-2 in place of 0-7.
We have discussed below Kruskal's MST implementations. Greedy Algorithms | Set 2 (Kruskal’s Minimum Spanning Tree Algorithm) Below are the steps for finding MST using Kruskal's algorithm
Here are some key points which will be useful for us in implementing the Kruskal’s algorithm using STL.
vector<pair<int, pair<int, int> > > edges;
Pseudo Code:
// Initialize result mst_weight = 0 // Create V single item sets for each vertex v parent[v] = v; rank[v] = 0; Sort all edges into non decreasing order by weight w for each (u, v) taken from the sorted list E do if FIND-SET(u) != FIND-SET(v) print edge(u, v) mst_weight += weight of edge(u, v) UNION(u, v)
Below is C++ implementation of above algorithm.
Edges of MST are 6 - 7 2 - 8 5 - 6 0 - 1 2 - 5 2 - 3 0 - 7 3 - 4 Weight of MST is 37
Time Complexity: O(E logV), here E is number of Edges and V is number of vertices in graph.
Auxiliary Space: O(V + E), here V is the number of vertices and E is the number of edges in the graph.
Optimization: The above code can be optimized to stop the main loop of Kruskal when number of selected edges become V-1. We know that MST has V-1 edges and there is no point iterating after V-1 edges are selected. We have not added this optimization to keep code simple.
Time complexity and step by step illustration are discussed in previous post on Kruskal's algorithm.