{"id":26508,"date":"2017-12-20T21:27:45","date_gmt":"2017-12-20T15:57:45","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26508"},"modified":"2017-12-20T21:27:45","modified_gmt":"2017-12-20T15:57:45","slug":"java-programming-backtracking-hamiltonian-cycle","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-backtracking-hamiltonian-cycle\/","title":{"rendered":"java programming &#8211; 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.<span id=\"more-19092\"><\/span> 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><em>Input:<\/em><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><em>Output:<\/em><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[ad type=&#8221;banner&#8221;]\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>(0)--(1)--(2)\r\n |   \/ \\   |\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) \r\n<\/pre>\n<div id=\"practice\">\n<h2 id=\"recommended-please-solve-it-on-practice-first-before-moving-on-to-the-solution\">Recommended: Please solve it on &#8220;<b><i><u>PRACTICE<\/u><\/i><\/b>&#8221; first, before moving on to the solution.<\/h2>\n<\/div>\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<p>java program:<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/* Java program for solution of Hamiltonian Cycle problem<br\/>   using backtracking *\/<br\/>class HamiltonianCycle<br\/>{<br\/>    final int V = 5;<br\/>    int path[];<br\/> <br\/>    \/* A utility function to check if the vertex v can be<br\/>       added at index &#039;pos&#039;in the Hamiltonian Cycle<br\/>       constructed so far (stored in &#039;path[]&#039;) *\/<br\/>    boolean isSafe(int v, int graph[][], int path[], int pos)<br\/>    {<br\/>        \/* Check if this vertex is an adjacent vertex of<br\/>           the previously 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<br\/>           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<br\/>       cycle problem *\/<br\/>    boolean hamCycleUtil(int graph[][], int path[], int pos)<br\/>    {<br\/>        \/* base case: If all vertices are included in<br\/>           Hamiltonian Cycle *\/<br\/>        if (pos == V)<br\/>        {<br\/>            \/\/ And if there is an edge from the last included<br\/>            \/\/ vertex to the 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<br\/>        \/\/ Hamiltonian Cycle. We don&#039;t try for 0 as we<br\/>        \/\/ 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<br\/>               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<br\/>           constructed so far, then return false *\/<br\/>        return false;<br\/>    }<br\/> <br\/>    \/* This function solves the Hamiltonian Cycle problem using<br\/>       Backtracking. It mainly uses hamCycleUtil() to solve the<br\/>       problem. It returns false if there is no Hamiltonian Cycle<br\/>       possible, otherwise return true and prints the path.<br\/>       Please note that there may be more than one solutions,<br\/>       this function prints one of the feasible solutions. *\/<br\/>    int hamCycle(int graph[][])<br\/>    {<br\/>        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.<br\/>           If there is a Hamiltonian Cycle, then the path can be<br\/>           started from any point of the cycle as the graph is<br\/>           undirected *\/<br\/>        path[0] = 0;<br\/>        if (hamCycleUtil(graph, path, 1) == false)<br\/>        {<br\/>            System.out.println(&quot;\\nSolution does not exist&quot;);<br\/>            return 0;<br\/>        }<br\/> <br\/>        printSolution(path);<br\/>        return 1;<br\/>    }<br\/> <br\/>    \/* A utility function to print solution *\/<br\/>    void printSolution(int path[])<br\/>    {<br\/>        System.out.println(&quot;Solution Exists: Following&quot; +<br\/>                           &quot; is one Hamiltonian Cycle&quot;);<br\/>        for (int i = 0; i &lt; V; i++)<br\/>            System.out.print(&quot; &quot; + path[i] + &quot; &quot;);<br\/> <br\/>        \/\/ Let us print the first vertex again to show the<br\/>        \/\/ complete cycle<br\/>        System.out.println(&quot; &quot; + path[0] + &quot; &quot;);<br\/>    }<br\/> <br\/>    \/\/ driver program to test above function<br\/>    public static void main(String args[])<br\/>    {<br\/>        HamiltonianCycle hamiltonian =<br\/>                                new HamiltonianCycle();<br\/>        \/* Let us create the following graph<br\/>           (0)--(1)--(2)<br\/>            |   \/ \\   |<br\/>            |  \/   \\  |<br\/>            | \/     \\ |<br\/>           (3)-------(4)    *\/<br\/>        int graph1[][] = {{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\/>        hamiltonian.hamCycle(graph1);<br\/> <br\/>        \/* Let us create the following graph<br\/>           (0)--(1)--(2)<br\/>            |   \/ \\   |<br\/>            |  \/   \\  |<br\/>            | \/     \\ |<br\/>           (3)       (4)    *\/<br\/>        int graph2[][] = {{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\/>        hamiltonian.hamCycle(graph2);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p>Output:<\/p>\n<pre>Solution Exists: Following is one Hamiltonian Cycle\r\n 0  1  2  4  3  0\r\n\r\nSolution does not exist\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>java programming &#8211; Backtracking &#8211; Hamiltonian Cycle &#8211; Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,73906,78521,2139],"tags":[75507,79012,79014,78968,78965,79011,78967,79013],"class_list":["post-26508","post","type-post","status-publish","format-standard","hentry","category-coding","category-graph-algorithms","category-hard-problems","category-java","tag-algorithm-for-finding-hamiltonian-cycle-in-an-undirected-graph","tag-c-program-for-hamiltonian-cycle-problem","tag-hamiltonian-cycle-algorithm-ppt","tag-hamiltonian-cycle-algorithm-using-backtracking-pdf","tag-hamiltonian-cycle-example","tag-hamiltonian-cycle-using-backtracking-example","tag-hamiltonian-path-algorithm-pseudocode","tag-time-complexity-of-hamiltonian-cycle-using-backtracking"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26508","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=26508"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26508\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26508"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26508"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26508"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}