{"id":3916,"date":"2023-06-30T18:15:09","date_gmt":"2023-06-30T12:45:09","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=3916"},"modified":"2023-06-30T18:16:26","modified_gmt":"2023-06-30T12:46:26","slug":"hamiltonian-path-problem","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/hamiltonian-path-problem\/","title":{"rendered":"Hamiltonian Path Problem"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement:<\/a><\/li><li><a href=\"#approach-backtracking\">Approach: Backtracking<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#practice-questions\">Practice Questions:<\/a><\/li><li><a href=\"#faq\">FAQ<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-what-is-the-time-and-space-complexity-of-the-backtracking-approach\">Q.1: What is the time and space complexity of the backtracking approach?<\/a><\/li><li><a href=\"#q2-what-is-a-hamiltonian-cycle\">Q.2: What is a Hamiltonian Cycle?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement:<\/h2>\n\n\n\n<p>Given an undirected graph<strong>. <\/strong>The task is to print all the Hamiltonian cycles present in the graph.<\/p>\n\n\n\n<p>A <strong>Hamiltonian Cycle<\/strong> is a cycle that traverses all the nodes of the graph exactly once and returns back to the starting point.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"509\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"Graph and Hamiltonian Cycle\"  class=\"wp-image-3979 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-1024x509.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-1024x509.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-300x149.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-768x382.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-1536x763.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-380x189.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-550x273.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-800x397.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle-1160x576.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/graph-and-Hamiltonian-Cycle.png 1552w\" ><\/figure>\n\n\n\n<p><strong>Example :<\/strong><\/p>\n\n\n\n<p><strong>Input :<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"624\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"Hamiltonian Path\"  class=\"wp-image-3981 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-1024x624.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-1024x624.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-300x183.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-768x468.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-380x231.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-550x335.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-800x487.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path-1160x707.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Hamiltonian-Path.png 1369w\" ><\/figure>\n\n\n\n<h2 id=\"approach-backtracking\">Approach: Backtracking<\/h2>\n\n\n\n<p>The problem can be solved using a backtracking approach. Follow the below steps to solve the problem.<\/p>\n\n\n\n<p><strong>Algorithm:<\/strong><\/p>\n\n\n\n<ul><li>Create an empty path array.<\/li><li>Add the vertex 0 to the array.<\/li><li>Start adding vertex 1 and other connected nodes and check if the current vertex can be included in the array or not.<\/li><li>This can be done by using a visiting array and checking if the vertex has already been visited or is adjacent to the previously added vertex.<\/li><li>If any such vertex is found, add it to the array and backtrack from that node.<\/li><li>Try every possible combination and if a path returns false, ignore the vertex and start iterating from the next vertex till all the nodes have been visited.<\/li><\/ul>\n\n\n\n<p><strong>Implementation of the Approach:<\/strong><\/p>\n\n\n\n<h3 id=\"c-code\">C++ Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">#define N 8\n\/\/vertices\nchar vertices[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\n\/\/adjacency matrix\nint adjacencyM[N][N]= {{0, 1, 0, 0, 0, 0, 0, 1},\n                       {1, 0, 1, 0, 0, 0, 0, 0},\n                       {0, 1, 0, 1, 0, 0, 0, 1},\n                       {0, 0, 1, 0, 1, 0, 1, 0},\n                       {0, 0, 0, 1, 0, 1, 0, 0},\n                       {0, 0, 0, 0, 1, 0, 1, 0},\n                       {0, 0, 0, 1, 0, 1, 0, 1},\n                       {1, 0, 1, 0, 0, 0, 1, 0}};\n \n\/\/list mapping of vertices to mark vertex visited\nint visited[N] {\n  0\n};\n \nclass Hamiltonian {\n  public:\n    \/\/start (&amp; end) vertex\n    int start;\n  \/\/stack used as list to store the path of the cycle\n  list &lt; int > cycle;\n  \/\/variable to mark if graph has the cycle\n  bool hasCycle = false;\n\/\/constructor\n  Hamiltonian(int start) {\n    this -> start = start;\n  }\n \n  \/\/method to initiate the search of the Hamiltonian cycle\n  void findCycle() {\n    \/\/add starting vertex to the list\n    cycle.push_back(start);\n \n    \/\/start searching the path\n    solve(start);\n  }\n \n  void solve(int vertex) {\n    \/\/Base condition: if the vertex is the start vertex\n    \/\/and all nodes have been visited (start vertex twice)\n    if (vertex == start &amp;&amp; cycle.size() == N + 1) {\n      hasCycle = true;\n \n      \/\/output the cycle\n      displayCycle();\n \n      \/\/return to explore more hamiltonian cycles\n      return;\n    }\n \n    \/\/iterate through the neighbor vertices\n    for (int i = 0; i &lt; N; i++) {\n      if (adjacencyM[vertex][i] == 1 &amp;&amp; visited[i] == 0) {\n        int nbr = i;\n        \/\/visit and add vertex to the cycle\n        visited[nbr] = 1;\n        cycle.push_back(nbr);\n \n        \/\/Go to the neighbor vertex to find the cycle\n        solve(nbr);\n   \/\/Backtrack\n        visited[nbr] = 0;\n        cycle.pop_back();\n      }\n    }\n  }\n \n  \/\/Function to display hamiltonian cycle\n  void displayCycle() {\n    cout &lt;&lt; \"[\";\n    for (int v: cycle) {\n      cout &lt;&lt; vertices[v] &lt;&lt; \" \";\n    }\n    cout &lt;&lt; \"] \\n\";\n  }\n};<\/pre>\n\n\n\n<h3 id=\"java-code\">Java Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> class Hamiltonian {\n  \/\/vertices\n  char vertices[];\n  \/\/adjacency matrix\n  int adjacencyM[][];\n  \/\/list mapping of vertices to mark vertex visited\n  int visited[];\n  \/\/start (&amp; end) vertex index\n  int start;\n  \/\/stack used as list to store the path of the cycle\n  Stack &lt; Integer > cycle = new Stack &lt; > ();\n  \/\/number of vertices in the graph\n  int N;\n  \/\/variable to mark if graph has the cycle\n  boolean hasCycle = false;\n \n  \/\/constructor\n  Hamiltonian(int start, char vertices[], int adjacencyM[][]) {\n    this.start = start;\n    this.vertices = vertices;\n    this.adjacencyM = adjacencyM;\n    this.N = vertices.length;\n    this.visited = new int[vertices.length];\n  }\n \n  \/\/method to initiate the search of the Hamiltonian cycle\n  public void findCycle() {\n    \/\/add starting vertex to the list\n    cycle.push(start);\n \n    \/\/start searching the path\n    solve(start);\n  }\n \n  private void solve(int vertex) {\n    \/\/Base condition: if the vertex is the start vertex\n    \/\/and all nodes have been visited (start vertex twice)\n    if (vertex == start &amp;&amp; cycle.size() == N + 1) {\n      hasCycle = true;\n \n      \/\/output the cycle\n      displayCycle();\n \n      \/\/return to explore more hamiltonian cycles\n      return;\n    }\n \n    \/\/iterate through the neighbor vertices\n    for (int i = 0; i &lt; N; i++) {\n      if (adjacencyM[vertex][i] == 1 &amp;&amp; visited[i] == 0) {\n        int nbr = i;\n        \/\/visit and add vertex to the cycle\n        visited[nbr] = 1;\n        cycle.push(nbr);\n \n        \/\/Go to the neighbor vertex to find the cycle\n        solve(nbr);\n \n        \/\/Backtrack\n        visited[nbr] = 0;\n    cycle.pop();\n      }\n    }\n  }\n \n  \/\/Method to display the path of the cycle\n  void displayCycle() {\n    \/\/converting vertex index to the name\n    List &lt; Character > names = new ArrayList &lt; > ();\n    for (int idx: cycle) {\n      names.add(vertices[idx]);\n    }\n    System.out.println(names);\n  }\n}\nclass Main {\n  public static void main(String[] args) {\n    \/\/vertices\n    char vertices[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\n    \/\/adjacency matrix\n    int adjacencyM[][]= {{0, 1, 0, 0, 0, 0, 0, 1},\n                         {1, 0, 1, 0, 0, 0, 0, 0},\n                         {0, 1, 0, 1, 0, 0, 0, 1},\n                         {0, 0, 1, 0, 1, 0, 1, 0},\n                         {0, 0, 0, 1, 0, 1, 0, 0},\n                         {0, 0, 0, 0, 1, 0, 1, 0},\n                         {0, 0, 0, 1, 0, 1, 0, 1},\n                         {1, 0, 1, 0, 0, 0, 1, 0}};\n \n    \/\/Driver code\n    Hamiltonian hamiltonian = new Hamiltonian(0,vertices, adjacencyM);\n    hamiltonian.findCycle();\n \n    \/\/if the graph doesn't have any Hamiltonian Cycle\n    if(!hamiltonian.hasCycle){\n      System.out.println(\"No Hamiltonian Cycle\");\n    }\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-code\">Python Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Hamiltonian:\n    def __init__(self, start):\n        # start (&amp; end) vertex\n        self.start = start\n \n        # list to store the cycle path\n        self.cycle = []\n \n        # variable to mark if graph has the cycle\n        self.hasCycle = False\n \n    # method to initiate the search of cycle\n    def findCycle(self):\n        # add starting vertex to the list\n        self.cycle.append(self.start)\n \n        # start the search of the hamiltonian cycle\n        self.solve(self.start)\n \n    # recursive function to implement backtracking\n    def solve(self, vertex):\n        # Base condition: if the vertex is the start vertex\n        # and all nodes have been visited (start vertex twice)\n        if vertex == self.start and len(self.cycle) == N + 1:\n            self.hasCycle = True\n \n            # output the cycle\n            self.displayCycle()\n \n            # return to explore more cycles\n            return\n \n        # iterate through the neighbor vertices\n        for i in range(len(vertices)):\n            if adjacencyM[vertex][i] == 1 and visited[i] == 0:\n                nbr = i\n # visit and add vertex to the cycle\n                visited[nbr] = 1\n                self.cycle.append(nbr)\n \n                # traverse the neighbor vertex to find the cycle\n                self.solve(nbr)\n \n                # Backtrack\n                visited[nbr] = 0\n                self.cycle.pop()\n \n    # function to display the hamiltonian class\n    def displayCycle(self):\n        names = []\n        for v in self.cycle:\n            names.append(vertices[v])\n        print(names)\n \nif __name__ == '__main__':\n  vertices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n  adjacencyM = [[0, 1, 0, 0, 0, 0, 0, 1],\n                [1, 0, 1, 0, 0, 0, 0, 0],\n                [0, 1, 0, 1, 0, 0, 0, 1],\n                [0, 0, 1, 0, 1, 0, 1, 0],\n                [0, 0, 0, 1, 0, 1, 0, 0],\n                [0, 0, 0, 0, 1, 0, 1, 0],\n                [0, 0, 0, 1, 0, 1, 0, 1],\n                [1, 0, 1, 0, 0, 0, 1, 0]]\n  #list mapping of vertices to mark vertex visited\n  visited = [0 for x in range(len(vertices))]\n \n  #number of vertices in the graph\n  N = 8\n \n  #Driver code\n  hamiltonian = Hamiltonian(0)\n  hamiltonian.findCycle()\n \n  #if the graph doesn't have any Hamiltonian Cycle\n  if not hamiltonian.hasCycle:\n print(\"No Hamiltonian Cycle\")<\/pre>\n\n\n\n<ul><li><strong>Time Complexity: <\/strong>O(N!), where N is the number of vertices.<\/li><li><strong>Space Complexity:<\/strong> O(1), as no extra space is used.<\/li><\/ul>\n\n\n\n<h2 id=\"practice-questions\">Practice Questions:<\/h2>\n\n\n\n<ul><li><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/cycle-in-undirected-graph\/\" target=\"_blank\">Cycle in Undirected Graph<\/a><\/li><\/ul>\n\n\n\n<h2 id=\"faq\">FAQ<\/h2>\n\n\n\n<h3 id=\"q1-what-is-the-time-and-space-complexity-of-the-backtracking-approach\"><span id=\"q-1-what-is-the-time-and-space-complexity-of-the-backtracking-approach\">Q.1: What is the time and space complexity of the backtracking approach?<\/span><\/h3>\n\n\n\n<p><strong>Ans: <\/strong>The time and space complexity of the backtracking approach. is O(N!) and O(1), where N is the number of vertices.<\/p>\n\n\n\n<h3 id=\"q2-what-is-a-hamiltonian-cycle\"><span id=\"q-2-what-is-a-hamiltonian-cycle\">Q.2: What is a Hamiltonian Cycle?<\/span><\/h3>\n\n\n\n<p><strong>Ans:<\/strong> A <strong>Hamiltonian Cycle<\/strong> is a cycle that traverses all the nodes of the graph exactly once and returns back to the starting point.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement: Given an undirected graph. The task is to print all the Hamiltonian cycles present in the&hellip;\n","protected":false},"author":5,"featured_media":3982,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[587],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3916"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=3916"}],"version-history":[{"count":6,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3916\/revisions"}],"predecessor-version":[{"id":21017,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3916\/revisions\/21017"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/3982"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=3916"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=3916"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=3916"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}