{"id":25978,"date":"2017-10-26T09:39:43","date_gmt":"2017-10-26T04:09:43","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25978"},"modified":"2017-10-26T09:39:43","modified_gmt":"2017-10-26T04:09:43","slug":"prims-minimum-spanning-tree-mst-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/prims-minimum-spanning-tree-mst-2\/","title":{"rendered":"CPP  Algorithm -Prim\u2019s Minimum Spanning Tree (MST)"},"content":{"rendered":"<p>We have discussed\u00a0Kruskal\u2019s algorithm for Minimum Spanning Tree. Like Kruskal\u2019s algorithm, Prim\u2019s algorithm is also a\u00a0Greedy algorithm. It starts with an empty spanning tree.<span id=\"more-27455\"><\/span> The idea is to maintain two sets of vertices. The first set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every step, it considers all the edges that connect the two sets, and picks the minimum weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing MST.<br \/>\nA group of edges that connects two set of vertices in a graph is called\u00a0cut in graph theory.\u00a0<em>So, at every step of Prim\u2019s algorithm, we find a cut (of two sets, one contains the vertices already included in MST and other contains rest of the verices), pick the minimum weight edge from the cut and include this vertex to MST Set (the set that contains already included vertices).<\/em><\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong><em>How does Prim\u2019s Algorithm Work?<\/em><\/strong> The idea behind Prim\u2019s algorithm is simple, a spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a\u00a0<em>Spanning\u00a0<\/em>Tree. And they must be connected with the minimum weight edge to make it a\u00a0<em>Minimum\u00a0<\/em>Spanning Tree.<\/p>\n<p><strong><em>Algorithm<\/em><\/strong><br \/>\n<strong>1)<\/strong> Create a set <em>mstSet<\/em> that keeps track of vertices already included in MST.<br \/>\n<strong>2)<\/strong> Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign key value as 0 for the first vertex so that it is picked first.<br \/>\n<strong>3)<\/strong> While mstSet doesn\u2019t include all vertices<br \/>\n\u2026.<strong>a)<\/strong> Pick a vertex <em>u<\/em> which is not there in <em>mstSet <\/em>and has minimum key value.<br \/>\n\u2026.<strong>b)<\/strong> Include <em>u <\/em>to mstSet.<br \/>\n\u2026.<strong>c)<\/strong> Update key value of all adjacent vertices of <em>u<\/em>. To update the key values, iterate through all adjacent vertices. For every adjacent vertex <em>v<\/em>, if weight of edge <em>u-v<\/em> is less than the previous key value of <em>v<\/em>, update the key value as weight of <em>u-v<\/em><\/p>\n<p>The idea of using key values is to pick the minimum weight edge from cut. The key values are used only for vertices which are not yet included in MST, the key value for these vertices indicate the minimum weight edges connecting them to the set of vertices included in MST.<\/p>\n<p>Let us understand with the following example:<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25994\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-11.png\" alt=\"Prim\u2019s Minimum Spanning Tree (MST)\" width=\"714\" height=\"333\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-11.png 714w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Fig-11-300x140.png 300w\" sizes=\"(max-width: 714px) 100vw, 714px\" \/><\/p>\n<p>The set <em>mstSet <\/em>is initially empty and keys assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum key value. The vertex 0 is picked, include it in <em>mstSet<\/em>. So <em>mstSet <\/em>becomes {0}. After including to <em>mstSet<\/em>, update key values of adjacent vertices. Adjacent vertices of 0 are 1 and 7. The key values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their key values, only the vertices with finite key values are shown. The vertices included in MST are shown in green color.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-25996\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST1.png\" alt=\"Prim\u2019s Minimum Spanning Tree (MST)\" width=\"80\" height=\"139\" \/><\/p>\n<p>Pick the vertex with minimum key value and not already included in MST (not in mstSET). The vertex 1 is picked and added to mstSet. So mstSet now becomes {0, 1}. Update the key values of adjacent vertices of 1. The key value of vertex 2 becomes 8.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-25998\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST2.png\" alt=\"Prim\u2019s Minimum Spanning Tree (MST)\" width=\"150\" height=\"139\" \/><\/p>\n<p>Pick the vertex with minimum key value and not already included in MST (not in mstSET). We can either pick vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0, 1, 7}. Update the key values of adjacent vertices of 7. The key value of vertex 6 and 8 becomes finite (7 and 1 respectively).<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26000\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST3.png\" alt=\"Prim\u2019s Minimum Spanning Tree (MST))\" width=\"150\" height=\"139\" \/><\/p>\n<p>Pick the vertex with minimum key value and not already included in MST (not in mstSET). Vertex 6 is picked. So mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent vertices of 6. The key value of vertex 5 and 8 are updated.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26008\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST4.png\" alt=\"Prim\u2019s Minimum Spanning Tree (MST))\" width=\"210\" height=\"139\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST4.png 210w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST4-130x86.png 130w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST4-187x124.png 187w\" sizes=\"(max-width: 210px) 100vw, 210px\" \/><\/p>\n<p>We repeat the above steps until <em>mstSet <\/em>includes all vertices of given graph. Finally, we get the following graph.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-26010\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/MST5.png\" alt=\"Prim\u2019s Minimum Spanning Tree (MST))\" width=\"260\" height=\"139\" \/><\/p>\n<p><strong><em>How to implement the above algorithm?<\/em><\/strong><br \/>\nWe use a boolean array mstSet[] to represent the set of vertices included in MST. If a value mstSet[v] is true, then vertex v is included in MST, otherwise not. Array key[] is used to store key values of all vertices. Another array parent[] to store indexes of parent nodes in MST. The parent array is the output array which is used to show the constructed MST.<\/p>\n<p><strong>C Program<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A C \/ C++ program for Prim&#039;s Minimum Spanning Tree (MST) algorithm. <br\/>\/\/ The program is for adjacency matrix representation of the graph<br\/> <br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;limits.h&gt;<br\/> <br\/>\/\/ Number of vertices in the graph<br\/>#define V 5<br\/> <br\/>\/\/ A utility function to find the vertex with minimum key value, from<br\/>\/\/ the set of vertices not yet included in MST<br\/>int minKey(int key[], bool mstSet[])<br\/>{<br\/>   \/\/ Initialize min value<br\/>   int min = INT_MAX, min_index;<br\/> <br\/>   for (int v = 0; v &lt; V; v++)<br\/>     if (mstSet[v] == false &amp;&amp; key[v] &lt; min)<br\/>         min = key[v], min_index = v;<br\/> <br\/>   return min_index;<br\/>}<br\/> <br\/>\/\/ A utility function to print the constructed MST stored in parent[]<br\/>int printMST(int parent[], int n, int graph[V][V])<br\/>{<br\/>   printf(&quot;Edge   Weight\\n&quot;);<br\/>   for (int i = 1; i &lt; V; i++)<br\/>      printf(&quot;%d - %d    %d \\n&quot;, parent[i], i, graph[i][parent[i]]);<br\/>}<br\/> <br\/>\/\/ Function to construct and print MST for a graph represented using adjacency<br\/>\/\/ matrix representation<br\/>void primMST(int graph[V][V])<br\/>{<br\/>     int parent[V]; \/\/ Array to store constructed MST<br\/>     int key[V];   \/\/ Key values used to pick minimum weight edge in cut<br\/>     bool mstSet[V];  \/\/ To represent set of vertices not yet included in MST<br\/> <br\/>     \/\/ Initialize all keys as INFINITE<br\/>     for (int i = 0; i &lt; V; i++)<br\/>        key[i] = INT_MAX, mstSet[i] = false;<br\/> <br\/>     \/\/ Always include first 1st vertex in MST.<br\/>     key[0] = 0;     \/\/ Make key 0 so that this vertex is picked as first vertex<br\/>     parent[0] = -1; \/\/ First node is always root of MST <br\/> <br\/>     \/\/ The MST will have V vertices<br\/>     for (int count = 0; count &lt; V-1; count++)<br\/>     {<br\/>        \/\/ Pick the minimum key vertex from the set of vertices<br\/>        \/\/ not yet included in MST<br\/>        int u = minKey(key, mstSet);<br\/> <br\/>        \/\/ Add the picked vertex to the MST Set<br\/>        mstSet[u] = true;<br\/> <br\/>        \/\/ Update key value and parent index of the adjacent vertices of<br\/>        \/\/ the picked vertex. Consider only those vertices which are not yet<br\/>        \/\/ included in MST<br\/>        for (int v = 0; v &lt; V; v++)<br\/> <br\/>           \/\/ graph[u][v] is non zero only for adjacent vertices of m<br\/>           \/\/ mstSet[v] is false for vertices not yet included in MST<br\/>           \/\/ Update the key only if graph[u][v] is smaller than key[v]<br\/>          if (graph[u][v] &amp;&amp; mstSet[v] == false &amp;&amp; graph[u][v] &lt;  key[v])<br\/>             parent[v]  = u, key[v] = graph[u][v];<br\/>     }<br\/> <br\/>     \/\/ print the constructed MST<br\/>     printMST(parent, V, graph);<br\/>}<br\/> <br\/> <br\/>\/\/ driver program to test above function<br\/>int main()<br\/>{<br\/>   \/* Let us create the following graph<br\/>          2    3<br\/>      (0)--(1)--(2)<br\/>       |   \/ \\   |<br\/>      6| 8\/   \\5 |7<br\/>       | \/     \\ |<br\/>      (3)-------(4)<br\/>            9          *\/<br\/>   int graph[V][V] = {{0, 2, 0, 6, 0},<br\/>                      {2, 0, 3, 8, 5},<br\/>                      {0, 3, 0, 0, 7},<br\/>                      {6, 8, 0, 0, 9},<br\/>                      {0, 5, 7, 9, 0},<br\/>                     };<br\/> <br\/>    \/\/ Print the solution<br\/>    primMST(graph);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<div class=\"responsive-tabs-wrapper\"><\/div>\n<p>Output:<\/p>\n<pre>Edge   Weight\r\n0 - 1    2\r\n1 - 2    3\r\n0 - 3    6\r\n1 - 4    5<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C++ Algorithm &#8211; Prim\u2019s Minimum Spanning Tree (MST) &#8211; Minimum spanning tree We have discussed Kruskal\u2019s algorithm for Minimum Spanning Tree.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[83515,1,73906,76379],"tags":[70772,76598,76603,76599,76602,70778,76601,76600],"class_list":["post-25978","post","type-post","status-publish","format-standard","hentry","category-c-programming-3","category-coding","category-graph-algorithms","category-minimum-spanning-tree","tag-kruskals-algorithm-minimum-spanning-tree","tag-prims-algorithm-c","tag-prims-algorithm-complexity","tag-prims-algorithm-geeksforgeeks","tag-prims-algorithm-java","tag-prims-algorithm-pseudocode","tag-prims-algorithm-vs-kruskals-algorithm","tag-prims-algorithm-youtube"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25978","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=25978"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25978\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25978"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25978"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25978"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}