{"id":26387,"date":"2017-12-21T20:56:55","date_gmt":"2017-12-21T15:26:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26387"},"modified":"2017-12-21T20:56:55","modified_gmt":"2017-12-21T15:26:55","slug":"greedy-algorithms-set-9-boruvkas-algorithm","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/greedy-algorithms-set-9-boruvkas-algorithm\/","title":{"rendered":"Greedy Algorithms | Set 9 (Boruvka\u2019s algorithm)"},"content":{"rendered":"<p>In this post, Boruvka\u2019s algorithm is discussed. Like Prim\u2019s and Kruskal\u2019s, Boruvka\u2019s algorithm is also a Greedy algorithm. Below is complete algorithm.<\/p>\n<pre>1) Input is a connected, weighted and directed graph.\r\n2) Initialize all vertices as individual components (or sets).\r\n3) Initialize MST as empty.\r\n4) While there are more than one components, do following\r\n   for each component.\r\n      a)  Find the closest weight edge that connects this \r\n          component to any other component.\r\n      b)  Add this closest edge to MST if not already added.  \r\n5) Return MST.\r\n<\/pre>\n<p>Below is the idea behind above algorithm (The idea is same as <a href=\"http:\/\/www.geeksforgeeks.org\/greedy-algorithms-set-5-prims-minimum-spanning-tree-mst-2\/\" target=\"_blank\" rel=\"noopener\">Prim\u2019s MST algorithm<\/a>).<\/p>\n<p><em>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.<\/em><\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Let us understand the algorithm with below example.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-26263\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Dijkstra\u2019s-Algorithm-for-Adjacency-List-Representation.png\" alt=\"Boruvka\u2019s algorithm\" width=\"717\" height=\"334\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Dijkstra\u2019s-Algorithm-for-Adjacency-List-Representation.png 717w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Dijkstra\u2019s-Algorithm-for-Adjacency-List-Representation-300x140.png 300w\" sizes=\"(max-width: 717px) 100vw, 717px\" \/><\/p>\n<p>Initially MST is empty. Every vertex is singe component as highlighted in blue color in below diagram.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26375\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/4-309.png\" alt=\"Boruvka\u2019s algorithm\" width=\"300\" height=\"139\" \/><\/p>\n<p>For every component, find the cheapest edge that connects it to some other component.<\/p>\n<pre><strong>Component                Cheapest Edge that connects \r\n                         it to some other component<\/strong>\r\n  {0}                           0-1\r\n  {1}                           0-1\r\n  {2}                           2-8\r\n  {3}                           2-3\r\n  {4}                           3-4\r\n  {5}                           5-6\r\n  {6}                           6-7\r\n  {7}                           6-7\r\n  {8}                           2-8<\/pre>\n<p>The cheapest edges are highlighted with green color<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26376\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/13-42.png\" alt=\"Boruvka\u2019s algorithm\" width=\"300\" height=\"139\" \/><\/p>\n<p>After above step, components are {{0,1}, {2,3,4,8}, {5,6,7}}. The components are encircled with blue color.<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26377\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/131.png\" alt=\"Boruvka\u2019s algorithm\" width=\"300\" height=\"139\" \/><\/p>\n<p>We again repeat the step, i.e., for every component, find the cheapest edge that connects it to some other component.<\/p>\n[ad type=&#8221;banner&#8221;]\n<pre><strong>Component                Cheapest Edge that connects \r\n                         it to some other component<\/strong>\r\n  {0,1}                        1-2 (or 0-7)\r\n  {2,3,4,8}                    2-5\r\n  {5,6,7}                      2-5<\/pre>\n<p>The cheapest edges are highlighted with green color. Now MST becomes<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26378\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/14-34.png\" alt=\"Boruvka\u2019s algorithm\" width=\"300\" height=\"139\" \/><\/p>\n<p>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.<\/p>\n<p><strong>Implementation:<\/strong><br \/>\nBelow is implementation of above algorithm. The input graph is represented as a collection of edges and <a href=\"http:\/\/www.geeksforgeeks.org\/union-find-algorithm-set-2-union-by-rank\/\" target=\"_blank\" rel=\"noopener\">union-find data structure<\/a> is used to keep track of components.<\/p>\n<p>python programming:<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Boruvka&#039;s algorithm to find Minimum Spanning<br\/># Tree of a given connected, undirected and weighted graph<br\/> <br\/>from collections import defaultdict<br\/> <br\/>#Class to represent a graph<br\/>class Graph:<br\/> <br\/>    def __init__(self,vertices):<br\/>        self.V= vertices #No. of vertices<br\/>        self.graph = [] # default dictionary to store graph<br\/>         <br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v,w):<br\/>        self.graph.append([u,v,w])<br\/> <br\/>    # A utility function to find set of an element i<br\/>    # (uses path compression technique)<br\/>    def find(self, parent, i):<br\/>        if parent[i] == i:<br\/>            return i<br\/>        return self.find(parent, parent[i])<br\/> <br\/>    # A function that does union of two sets of x and y<br\/>    # (uses union by rank)<br\/>    def union(self, parent, rank, x, y):<br\/>        xroot = self.find(parent, x)<br\/>        yroot = self.find(parent, y)<br\/> <br\/>        # Attach smaller rank tree under root of high rank tree<br\/>        # (Union by Rank)<br\/>        if rank[xroot] &lt; rank[yroot]:<br\/>            parent[xroot] = yroot<br\/>        elif rank[xroot] &gt; rank[yroot]:<br\/>            parent[yroot] = xroot<br\/>        #If ranks are same, then make one as root and increment<br\/>        # its rank by one<br\/>        else :<br\/>            parent[yroot] = xroot<br\/>            rank[xroot] += 1<br\/> <br\/>    # The main function to construct MST using Kruskal&#039;s algorithm<br\/>    def boruvkaMST(self):<br\/>        parent = []; rank = []; <br\/> <br\/>        # An array to store index of the cheapest edge of<br\/>        # subset. It store [u,v,w] for each component<br\/>        cheapest =[]<br\/> <br\/>        # Initially there are V different trees.<br\/>        # Finally there will be one tree that will be MST<br\/>        numTrees = self.V<br\/>        MSTweight = 0<br\/> <br\/>        # Create V subsets with single elements<br\/>        for node in range(self.V):<br\/>            parent.append(node)<br\/>            rank.append(0)<br\/>            cheapest =[-1] * self.V<br\/>     <br\/>        # Keep combining components (or sets) until all<br\/>        # compnentes are not combined into single MST<br\/> <br\/>        while numTrees &gt; 1:<br\/> <br\/>            # Traverse through all edges and update<br\/>            # cheapest of every component<br\/>            for i in range(len(self.graph)):<br\/> <br\/>                # Find components (or sets) of two corners<br\/>                # of current edge<br\/>                u,v,w =  self.graph[i]<br\/>                set1 = self.find(parent, u)<br\/>                set2 = self.find(parent ,v)<br\/> <br\/>                # If two corners of current edge belong to<br\/>                # same set, ignore current edge. Else check if <br\/>                # current edge is closer to previous<br\/>                # cheapest edges of set1 and set2<br\/>                if set1 != set2:    <br\/>                     <br\/>                    if cheapest[set1] == -1 or cheapest[set1][2] &gt; w :<br\/>                        cheapest[set1] = [u,v,w] <br\/> <br\/>                    if cheapest[set2] == -1 or cheapest[set2][2] &gt; w :<br\/>                        cheapest[set2] = [u,v,w]<br\/> <br\/>            # Consider the above picked cheapest edges and add them<br\/>            # to MST<br\/>            for node in range(self.V):<br\/> <br\/>                #Check if cheapest for current set exists<br\/>                if cheapest[node] != -1:<br\/>                    u,v,w = cheapest[node]<br\/>                    set1 = self.find(parent, u)<br\/>                    set2 = self.find(parent ,v)<br\/> <br\/>                    if set1 != set2 :<br\/>                        MSTweight += w<br\/>                        self.union(parent, rank, set1, set2)<br\/>                        print (&quot;Edge %d-%d with weight %d included in MST&quot; % (u,v,w))<br\/>                        numTrees = numTrees - 1<br\/>             <br\/>            #reset cheapest array<br\/>            cheapest =[-1] * self.V<br\/> <br\/>             <br\/>        print (&quot;Weight of MST is %d&quot; % MSTweight)<br\/>                           <br\/> <br\/>     <br\/>g = Graph(4)<br\/>g.addEdge(0, 1, 10)<br\/>g.addEdge(0, 2, 6)<br\/>g.addEdge(0, 3, 5)<br\/>g.addEdge(1, 3, 15)<br\/>g.addEdge(2, 3, 4)<br\/> <br\/>g.boruvkaMST()<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Edge 0-3 included in MST\r\nEdge 0-1 included in MST\r\nEdge 2-3 included in MST\r\nWeight of MST is 19<\/pre>\n<p><strong>Interesting Facts about Boruvka\u2019s algorithm:<\/strong><br \/>\n1) Time Complexity of Boruvka\u2019s algorithm is O(E log V) which is same as Kruskal\u2019s and Prim\u2019s algorithms.<\/p>\n<p>2) Boruvka\u2019s algorithm is used as a step in a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Expected_linear_time_MST_algorithm\" target=\"_blank\" rel=\"noopener\">faster randomized algorithm that works in linear time O(E)<\/a>.<\/p>\n<p>3) Boruvka\u2019s algorithm is the oldest minimum spanning tree algorithm was discovered by Boruuvka in 1926, long before computers even existed. The algorithm was published as a method of constructing an efficient electricity network.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Greedy Algorithms Boruvka\u2019s algorithm &#8211; Minimum Spanning Tree Like Prim\u2019s and Kruskal\u2019s, Boruvka\u2019s algorithm is also a Greedy algorithm.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,1,83618],"tags":[78515,83640,83639,83645,78514,78517,78516,83644,83641,78519,78520,78518,83643,83642,83638],"class_list":["post-26387","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-coding","category-greedy-algorithms","tag-boruvka-algorithm-example","tag-boruvka-algorithm-ppt","tag-boruvka-algorithm-proof-of-correctness","tag-boruvka-vs-prim-vs-kruskal","tag-boruvkas-algorithm-c-code","tag-boruvkas-algorithm-implementation","tag-boruvkas-algorithm-java","tag-boruvkas-algorithm-parallel","tag-boruvkas-algorithm-pdf","tag-boruvkas-algorithm-pseudocode-boruvka-algorithm-ppt","tag-boruvkas-algorithm-python","tag-sollins-algorithm","tag-sollins-algorithm-in-data-structure","tag-sollins-algorithm-in-ds","tag-what-is-sollins-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26387","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26387"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26387\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26387"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26387"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26387"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}