{"id":25804,"date":"2017-10-25T20:49:31","date_gmt":"2017-10-25T15:19:31","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25804"},"modified":"2017-10-25T20:49:31","modified_gmt":"2017-10-25T15:19:31","slug":"backtracking-set-6-hamiltonian-cycle","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/backtracking-set-6-hamiltonian-cycle\/","title":{"rendered":"C++ Programming-Backtracking Set 6 (Hamiltonian Cycle)"},"content":{"rendered":"<p>Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. Determine whether a given graph contains Hamiltonian Cycle or not. If it contains, then print the path. Following are the input and output of the required function.<\/p>\n<p>Input:<br \/>\nA 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.<\/p>\n<p>Output:<br \/>\nAn array path[V] that should contain the Hamiltonian Path. path[i] should represent the ith vertex in the Hamiltonian Path. The code should also return false if there is no Hamiltonian Cycle in the graph.<\/p>\n<p>For example, a Hamiltonian Cycle in the following graph is {0, 1, 2, 4, 3, 0}. There are more Hamiltonian Cycles in the graph like {0, 3, 4, 2, 1, 0}<\/p>\n<pre>|   \/ \\   |\r\n |  \/   \\  | \r\n | \/     \\ |\r\n(3)-------(4)\r\n<\/pre>\n<p>And the following graph doesn\u2019t contain any Hamiltonian Cycle.<\/p>\n<pre>(0)--(1)--(2)\r\n |   \/ \\   |\r\n |  \/   \\  | \r\n | \/     \\ |\r\n(3)      (4)<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Naive Algorithm<\/strong><br \/>\nGenerate all possible configurations of vertices and print a configuration that satisfies the given constraints. There will be n! (n factorial) configurations.<\/p>\n<pre>while there are untried conflagrations\r\n{\r\n   generate the next configuration\r\n   if ( there are edges between two consecutive vertices of this\r\n      configuration and there is an edge from the last vertex to \r\n      the first ).\r\n   {\r\n      print this configuration;\r\n      break;\r\n   }\r\n}\r\n<\/pre>\n<p><strong>Backtracking Algorithm<\/strong><br \/>\nCreate an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. Before adding a vertex, check for whether it is adjacent to the previously added vertex and not already added. If we find such a vertex, we add the vertex as part of the solution. If we do not find a vertex then we return false.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Implementation of Backtracking solution<\/strong><br \/>\nFollowing are implementations of the Backtracking solution.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/* C\/C++ program for solution of Hamiltonian Cycle problem<br\/>   using backtracking *\/<br\/>#include&lt;stdio.h&gt;<br\/> <br\/>\/\/ Number of vertices in the graph<br\/>#define V 5<br\/> <br\/>void printSolution(int path[]);<br\/> <br\/>\/* A utility function to check if the vertex v can be added at<br\/>   index &#039;pos&#039; in the Hamiltonian Cycle constructed so far (stored<br\/>   in &#039;path[]&#039;) *\/<br\/>bool isSafe(int v, bool graph[V][V], int path[], int pos)<br\/>{<br\/>    \/* Check if this vertex is an adjacent vertex of the previously<br\/>       added vertex. *\/<br\/>    if (graph [ path[pos-1] ][ v ] == 0)<br\/>        return false;<br\/> <br\/>    \/* Check if the vertex has already been included.<br\/>      This step can be optimized by creating an array of size V *\/<br\/>    for (int i = 0; i &lt; pos; i++)<br\/>        if (path[i] == v)<br\/>            return false;<br\/> <br\/>    return true;<br\/>}<br\/> <br\/>\/* A recursive utility function to solve hamiltonian cycle problem *\/<br\/>bool hamCycleUtil(bool graph[V][V], int path[], int pos)<br\/>{<br\/>    \/* base case: If all vertices are included in Hamiltonian Cycle *\/<br\/>    if (pos == V)<br\/>    {<br\/>        \/\/ And if there is an edge from the last included vertex to the<br\/>        \/\/ first vertex<br\/>        if ( graph[ path[pos-1] ][ path[0] ] == 1 )<br\/>           return true;<br\/>        else<br\/>          return false;<br\/>    }<br\/> <br\/>    \/\/ Try different vertices as a next candidate in Hamiltonian Cycle.<br\/>    \/\/ We don&#039;t try for 0 as we included 0 as starting point in in hamCycle()<br\/>    for (int v = 1; v &lt; V; v++)<br\/>    {<br\/>        \/* Check if this vertex can be added to Hamiltonian Cycle *\/<br\/>        if (isSafe(v, graph, path, pos))<br\/>        {<br\/>            path[pos] = v;<br\/> <br\/>            \/* recur to construct rest of the path *\/<br\/>            if (hamCycleUtil (graph, path, pos+1) == true)<br\/>                return true;<br\/> <br\/>            \/* If adding vertex v doesn&#039;t lead to a solution,<br\/>               then remove it *\/<br\/>            path[pos] = -1;<br\/>        }<br\/>    }<br\/> <br\/>    \/* If no vertex can be added to Hamiltonian Cycle constructed so far,<br\/>       then return false *\/<br\/>    return false;<br\/>}<br\/> <br\/>\/* This function solves the Hamiltonian Cycle problem using Backtracking.<br\/>  It mainly uses hamCycleUtil() to solve the problem. It returns false<br\/>  if there is no Hamiltonian Cycle possible, otherwise return true and<br\/>  prints the path. Please note that there may be more than one solutions,<br\/>  this function prints one of the feasible solutions. *\/<br\/>bool hamCycle(bool graph[V][V])<br\/>{<br\/>    int *path = new int[V];<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        path[i] = -1;<br\/> <br\/>    \/* Let us put vertex 0 as the first vertex in the path. If there is<br\/>       a Hamiltonian Cycle, then the path can be started from any point<br\/>       of the cycle as the graph is undirected *\/<br\/>    path[0] = 0;<br\/>    if ( hamCycleUtil(graph, path, 1) == false )<br\/>    {<br\/>        printf(&quot;\\nSolution does not exist&quot;);<br\/>        return false;<br\/>    }<br\/> <br\/>    printSolution(path);<br\/>    return true;<br\/>}<br\/> <br\/>\/* A utility function to print solution *\/<br\/>void printSolution(int path[])<br\/>{<br\/>    printf (&quot;Solution Exists:&quot;<br\/>            &quot; Following is one Hamiltonian Cycle \\n&quot;);<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        printf(&quot; %d &quot;, path[i]);<br\/> <br\/>    \/\/ Let us print the first vertex again to show the complete cycle<br\/>    printf(&quot; %d &quot;, path[0]);<br\/>    printf(&quot;\\n&quot;);<br\/>}<br\/> <br\/>\/\/ driver program to test above function<br\/>int main()<br\/>{<br\/>   \/* Let us create the following graph<br\/>      (0)--(1)--(2)<br\/>       |   \/ \\   |<br\/>       |  \/   \\  |<br\/>       | \/     \\ |<br\/>      (3)-------(4)    *\/<br\/>   bool graph1[V][V] = {{0, 1, 0, 1, 0},<br\/>                      {1, 0, 1, 1, 1},<br\/>                      {0, 1, 0, 0, 1},<br\/>                      {1, 1, 0, 0, 1},<br\/>                      {0, 1, 1, 1, 0},<br\/>                     };<br\/> <br\/>    \/\/ Print the solution<br\/>    hamCycle(graph1);<br\/> <br\/>   \/* Let us create the following graph<br\/>      (0)--(1)--(2)<br\/>       |   \/ \\   |<br\/>       |  \/   \\  |<br\/>       | \/     \\ |<br\/>      (3)       (4)    *\/<br\/>    bool graph2[V][V] = {{0, 1, 0, 1, 0},<br\/>                      {1, 0, 1, 1, 1},<br\/>                      {0, 1, 0, 0, 1},<br\/>                      {1, 1, 0, 0, 0},<br\/>                      {0, 1, 1, 0, 0},<br\/>                     };<br\/> <br\/>    \/\/ Print the solution<br\/>    hamCycle(graph2);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C++ Programming-Backtracking Set 6 (Hamiltonian Cycle) &#8211; Backtracking &#8211; Hamiltonian Path in an undirected graph is a path that visits each vertex exactly.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,73907,83515,1],"tags":[75507,75502,75504,74813,75506,75501,75505,75503],"class_list":["post-25804","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-backtracking-algorithm","category-c-programming-3","category-coding","tag-algorithm-for-finding-hamiltonian-cycle-in-an-undirected-graph","tag-euler-cycle","tag-hamiltonian-circuit-real-life-example","tag-hamiltonian-cycle-algorithm-using-backtracking","tag-hamiltonian-cycle-algorithm-using-backtracking-in-c","tag-hamiltonian-cycle-np-complete","tag-rudrata-cycle","tag-shortest-hamiltonian-path"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25804","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=25804"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25804\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25804"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25804"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25804"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}