{"id":26357,"date":"2017-10-26T21:11:23","date_gmt":"2017-10-26T15:41:23","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26357"},"modified":"2017-10-26T21:11:23","modified_gmt":"2017-10-26T15:41:23","slug":"greedy-algorithms-set-2-kruskals-minimum-spanning-tree-algorithm-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/greedy-algorithms-set-2-kruskals-minimum-spanning-tree-algorithm-2\/","title":{"rendered":"Greedy Algorithms | Set 2 (Kruskal\u2019s Minimum Spanning Tree Algorithm)"},"content":{"rendered":"<p><em>What is Minimum Spanning Tree?<\/em><br \/>\nGiven a connected and undirected graph, a <em>spanning tree<\/em> of that graph is a subgraph that is a tree and connects all the vertices together. <span id=\"more-26604\"><\/span>A single graph can have many different spanning trees. A <em>minimum spanning tree (MST)<\/em> or minimum weight spanning tree for a weighted, connected and undirected graph is a spanning tree with weight less than or equal to the weight of every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge of the spanning tree.<\/p>\n<p><em>How many edges does a minimum spanning tree has?<\/em><br \/>\nA minimum spanning tree has (V \u2013 1) edges where V is the number of vertices in the given graph.<\/p>\n<p><em>What are the applications of Minimum Spanning Tree?<\/em><br \/>\nSee <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/11110\" target=\"_blank\" rel=\"noopener\">this <\/a>for applications of MST.<\/p>\n[ad type=\u201dbanner\u201d]\n<p>Below are the steps for finding MST using Kruskal\u2019s algorithm:<\/p>\n<pre><strong>1.<\/strong> Sort all the edges in non-decreasing order of their weight.\r\n\r\n<strong>2.<\/strong> Pick the smallest edge. Check if it forms a cycle with the spanning tree \r\nformed so far. If cycle is not formed, include this edge. Else, discard it.  \r\n\r\n<strong>3.<\/strong> Repeat step#2 until there are (V-1) edges in the spanning tree.<\/pre>\n<p>The step#2 uses <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/26350\" target=\"_blank\" rel=\"noopener\">Union-Find algorithm<\/a> to detect cycle. So we recommend to read following post as a prerequisite.<br \/>\n<a href=\"http:\/\/www.geeksforgeeks.org\/union-find\/\" target=\"_blank\" rel=\"noopener\">Union-Find Algorithm | Set 1 (Detect Cycle in a Graph)<\/a><br \/>\n<a href=\"http:\/\/www.geeksforgeeks.org\/union-find-algorithm-set-2-union-by-rank\/\" target=\"_blank\" rel=\"noopener\">Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)<\/a><\/p>\n<p>The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a cycle in the MST constructed so far. Let us understand it with an example: Consider the below input graph.<\/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=\"Kruskal\u2019s Minimum Spanning Tree 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>The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 \u2013 1) = 8 edges.<\/p>\n<pre>After sorting:\r\nWeight   Src    Dest\r\n1         7      6\r\n2         8      2\r\n2         6      5\r\n4         0      1\r\n4         2      5\r\n6         8      6\r\n7         2      3\r\n7         7      8\r\n8         0      7\r\n8         1      2\r\n9         3      4\r\n10        5      4\r\n11        1      7\r\n14        3      5<\/pre>\n<p><strong>1.<\/strong> <em>Pick edge 7-6:<\/em> No cycle is formed, include it.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26318\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-11-2.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm)\" width=\"264\" height=\"72\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-11-2.png 264w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-11-2-260x72.png 260w\" sizes=\"(max-width: 264px) 100vw, 264px\" \/><\/p>\n<p><strong>2.<\/strong> <em>Pick edge 8-2:<\/em> No cycle is formed, include it.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26317\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-2-241x300.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm)\" width=\"241\" height=\"300\" \/><\/p>\n<p><strong>3.<\/strong> <em>Pick edge 6-5:<\/em> No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26326\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-3-300x232.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"232\" \/><\/p>\n<p><strong>4.<\/strong> <em>Pick edge 0-1:<\/em> No cycle is formed, include it<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26328\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-4-300x175-1.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>5.<\/strong> <em>Pick edge 2-5:<\/em> No cycle is formed, include it.<\/p>\n<p><strong>6.<\/strong><em> Pick edge 8-6: <\/em>Since including this edge results in cycle, discard it.<\/p>\n<p><strong>7.<\/strong> <em>Pick edge 2-3:<\/em> No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26331\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-6-300x175.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm)\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>8.<\/strong> <em>Pick edge 7-8:<\/em> Since including this edge results in cycle, discard it.<\/p>\n<p><strong>9.<\/strong> <em>Pick edge 0-7:<\/em> No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26336\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-7-300x175.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm)\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>10.<\/strong> <em>Pick edge 1-2: <\/em>Since including this edge results in cycle, discard it.<\/p>\n<p><strong>11.<\/strong> <em>Pick edge 3-4:<\/em> No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26340\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/fig8new.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm)\" width=\"712\" height=\"328\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/fig8new.png 712w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/fig8new-300x138.png 300w\" sizes=\"(max-width: 712px) 100vw, 712px\" \/><\/p>\n<p>\u00a0<\/p>\n<p>Python programming:<\/p>\n[pastacode lang=\u201dpython\u201d manual=\u201d%23%20Python%20program%20for%20Kruskal\u2019s%20algorithm%20to%20find%20Minimum%20Spanning%20Tree%0A%23%20of%20a%20given%20connected%2C%20undirected%20and%20weighted%20graph%0A%20%0Afrom%20collections%20import%20defaultdict%0A%20%0A%23Class%20to%20represent%20a%20graph%0Aclass%20Graph%3A%0A%20%0A%20%20%20%20def%20__init__(self%2Cvertices)%3A%0A%20%20%20%20%20%20%20%20self.V%3D%20vertices%20%23No.%20of%20vertices%0A%20%20%20%20%20%20%20%20self.graph%20%3D%20%5B%5D%20%23%20default%20dictionary%20to%20store%20graph%0A%20%20%20%20%20%20%20%20%20%0A%20%20%0A%20%20%20%20%23%20function%20to%20add%20an%20edge%20to%20graph%0A%20%20%20%20def%20addEdge(self%2Cu%2Cv%2Cw)%3A%0A%20%20%20%20%20%20%20%20self.graph.append(%5Bu%2Cv%2Cw%5D)%0A%20%0A%20%20%20%20%23%20A%20utility%20function%20to%20find%20set%20of%20an%20element%20i%0A%20%20%20%20%23%20(uses%20path%20compression%20technique)%0A%20%20%20%20def%20find(self%2C%20parent%2C%20i)%3A%0A%20%20%20%20%20%20%20%20if%20parent%5Bi%5D%20%3D%3D%20i%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20i%0A%20%20%20%20%20%20%20%20return%20self.find(parent%2C%20parent%5Bi%5D)%0A%20%0A%20%20%20%20%23%20A%20function%20that%20does%20union%20of%20two%20sets%20of%20x%20and%20y%0A%20%20%20%20%23%20(uses%20union%20by%20rank)%0A%20%20%20%20def%20union(self%2C%20parent%2C%20rank%2C%20x%2C%20y)%3A%0A%20%20%20%20%20%20%20%20xroot%20%3D%20self.find(parent%2C%20x)%0A%20%20%20%20%20%20%20%20yroot%20%3D%20self.find(parent%2C%20y)%0A%20%0A%20%20%20%20%20%20%20%20%23%20Attach%20smaller%20rank%20tree%20under%20root%20of%20high%20rank%20tree%0A%20%20%20%20%20%20%20%20%23%20(Union%20by%20Rank)%0A%20%20%20%20%20%20%20%20if%20rank%5Bxroot%5D%20%3C%20rank%5Byroot%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20parent%5Bxroot%5D%20%3D%20yroot%0A%20%20%20%20%20%20%20%20elif%20rank%5Bxroot%5D%20%3E%20rank%5Byroot%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20parent%5Byroot%5D%20%3D%20xroot%0A%20%20%20%20%20%20%20%20%23If%20ranks%20are%20same%2C%20then%20make%20one%20as%20root%20and%20increment%0A%20%20%20%20%20%20%20%20%23%20its%20rank%20by%20one%0A%20%20%20%20%20%20%20%20else%20%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20parent%5Byroot%5D%20%3D%20xroot%0A%20%20%20%20%20%20%20%20%20%20%20%20rank%5Bxroot%5D%20%2B%3D%201%0A%20%0A%20%20%20%20%23%20The%20main%20function%20to%20construct%20MST%20using%20Kruskal\u2019s%20algorithm%0A%20%20%20%20def%20KruskalMST(self)%3A%0A%20%0A%20%20%20%20%20%20%20%20result%20%3D%5B%5D%20%23This%20will%20store%20the%20resultant%20MST%0A%20%0A%20%20%20%20%20%20%20%20i%20%3D%200%20%23%20An%20index%20variable%2C%20used%20for%20sorted%20edges%0A%20%20%20%20%20%20%20%20e%20%3D%200%20%23%20An%20index%20variable%2C%20used%20for%20result%5B%5D%0A%20%0A%20%20%20%20%20%20%20%20%23Step%201%3A%20%20Sort%20all%20the%20edges%20in%20non-decreasing%20order%20of%20their%0A%20%20%20%20%20%20%20%20%23%20weight.%20%20If%20we%20are%20not%20allowed%20to%20change%20the%20given%20graph%2C%20we%0A%20%20%20%20%20%20%20%20%23%20can%20create%20a%20copy%20of%20graph%0A%20%20%20%20%20%20%20%20self.graph%20%3D%20%20sorted(self.graph%2Ckey%3Dlambda%20item%3A%20item%5B2%5D)%0A%20%20%20%20%20%20%20%20%23print%20self.graph%0A%20%0A%20%20%20%20%20%20%20%20parent%20%3D%20%5B%5D%20%3B%20rank%20%3D%20%5B%5D%0A%20%0A%20%20%20%20%20%20%20%20%23%20Create%20V%20subsets%20with%20single%20elements%0A%20%20%20%20%20%20%20%20for%20node%20in%20range(self.V)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20parent.append(node)%0A%20%20%20%20%20%20%20%20%20%20%20%20rank.append(0)%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%23%20Number%20of%20edges%20to%20be%20taken%20is%20equal%20to%20V-1%0A%20%20%20%20%20%20%20%20while%20e%20%3C%20self.V%20-1%20%3A%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20Step%202%3A%20Pick%20the%20smallest%20edge%20and%20increment%20the%20index%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20for%20next%20iteration%0A%20%20%20%20%20%20%20%20%20%20%20%20u%2Cv%2Cw%20%3D%20%20self.graph%5Bi%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%3D%20i%20%2B%201%0A%20%20%20%20%20%20%20%20%20%20%20%20x%20%3D%20self.find(parent%2C%20u)%0A%20%20%20%20%20%20%20%20%20%20%20%20y%20%3D%20self.find(parent%20%2Cv)%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20If%20including%20this%20edge%20does\u2019t%20cause%20cycle%2C%20include%20it%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20in%20result%20and%20increment%20the%20index%20of%20result%20for%20next%20edge%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20x%20!%3D%20y%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%20%3D%20e%20%2B%201%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20result.append(%5Bu%2Cv%2Cw%5D)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20self.union(parent%2C%20rank%2C%20x%2C%20y)%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20Else%20discard%20the%20edge%0A%20%0A%20%20%20%20%20%20%20%20%23%20print%20the%20contents%20of%20result%5B%5D%20to%20display%20the%20built%20MST%0A%20%20%20%20%20%20%20%20print%20%22Following%20are%20the%20edges%20in%20the%20constructed%20MST%22%0A%20%20%20%20%20%20%20%20for%20u%2Cv%2Cweight%20%20in%20result%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%23print%20str(u)%20%2B%20%22%20\u2013%20%22%20%2B%20str(v)%20%2B%20%22%20%3D%3D%20%22%20%2B%20str(weight)%0A%20%20%20%20%20%20%20%20%20%20%20%20print%20(%22%25d%20\u2013%20%25d%20%3D%3D%20%25d%22%20%25%20(u%2Cv%2Cweight))%0A%20%0A%20%0Ag%20%3D%20Graph(4)%0Ag.addEdge(0%2C%201%2C%2010)%0Ag.addEdge(0%2C%202%2C%206)%0Ag.addEdge(0%2C%203%2C%205)%0Ag.addEdge(1%2C%203%2C%2015)%0Ag.addEdge(2%2C%203%2C%204)%0A%20%0Ag.KruskalMST()\u201d message=\u201d\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<div class=\"line number1 index0 alt2\"><code class=\"python comments\"><\/code><code class=\"python plain\"><\/code><\/div>\n<pre>Following are the edges in the constructed MST\r\n2 -- 3 == 4\r\n0 -- 3 == 5\r\n0 -- 1 == 10<\/pre>\n<p><strong>Time Complexity:<\/strong> O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time. After sorting, we iterate through all edges and apply find-union algorithm. The find and union operations can take atmost O(LogV) time. So overall complexity is O(ELogE + ELogV) time. The value of E can be atmost O(V<sup>2<\/sup>), so O(LogV) are O(LogE) same. Therefore, overall time complexity is O(ElogE) or O(ElogV)<\/p>\n[ad type=\u201dbanner\u201d]\n","protected":false},"excerpt":{"rendered":"<p>Kruskal\u2019s Minimum Spanning Tree Algorithm) &#8211; Minimum Spanning Tree A single graph can have many different spanning trees. A minimum spanning tree (MST).<\/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,76379],"tags":[70774,78372,70781,78371,78374,78373,70770,70804],"class_list":["post-26357","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-coding","category-minimum-spanning-tree","tag-kruskals-algorithm-c","tag-kruskals-algorithm-geeksforgeeks","tag-kruskals-algorithm-in-c","tag-kruskals-algorithm-java","tag-kruskals-algorithm-pseudocode","tag-kruskals-algorithm-time-complexity","tag-prims-algorithm-example","tag-prims-algorithm-minimum-spanning-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26357","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=26357"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26357\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26357"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26357"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26357"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}