![]() |
VOOZH | about |
We have discussed the following topics on Minimum Spanning Tree.
Applications of Minimum Spanning Tree Problem
Kruskal’s Minimum Spanning Tree Algorithm
Prim’s Minimum Spanning Tree Algorithm
In this post, Boruvka's algorithm is discussed. Like Prim's and Kruskal's, Boruvka’s algorithm is also a Greedy algorithm. Below is a complete algorithm.
1) Input is a connected, weighted and un-directed graph. 2) Initialize all vertices as individual components (or sets). 3) Initialize MST as empty. 4) While there are more than one components, do following for each component. a) Find the closest weight edge that connects this component to any other component. b) Add this closest edge to MST if not already added. 5) Return MST.
Below is the idea behind the above algorithm (The idea is the same as Prim's MST algorithm).
A spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.
Let us understand the algorithm in the below example.
Initially, MST is empty. Every vertex is single component as highlighted in blue color in the below diagram.
For every component, find the cheapest edge that connects it to some other component.
Component Cheapest Edge that connects
it to some other component
{0} 0-1
{1} 0-1
{2} 2-8
{3} 2-3
{4} 3-4
{5} 5-6
{6} 6-7
{7} 6-7
{8} 2-8
The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7}.
After above step, components are {{0,1}, {2,3,4,8}, {5,6,7}}. The components are encircled with blue color.
We again repeat the step, i.e., for every component, find the cheapest edge that connects it to some other component.
Component Cheapest Edge that connects
it to some other component
{0,1} 1-2 (or 0-7)
{2,3,4,8} 2-5
{5,6,7} 2-5
The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7, 1-2, 2-5}
At this stage, there is only one component {0, 1, 2, 3, 4, 5, 6, 7, 8} which has all edges. Since there is only one component left, we stop and return MST.
Implementation: Below is the implementation of the above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components.
Edge 0-3 with weight 5 included in MST Edge 0-1 with weight 10 included in MST Edge 2-3 with weight 4 included in MST Weight of MST is 19
Interesting Facts about Boruvka’s algorithm:
Space complexity: The space complexity of Boruvka’s algorithm is O(V).
Exercise:
The above code assumes that the input graph is connected and it fails if a disconnected graph is given. Extend the above algorithm so that it works for a disconnected graph also and produces a forest.