{"id":2913,"date":"2023-06-13T10:20:59","date_gmt":"2023-06-13T04:50:59","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=2913"},"modified":"2023-06-13T10:24:29","modified_gmt":"2023-06-13T04:54:29","slug":"tower-of-hanoi","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/tower-of-hanoi\/","title":{"rendered":"Tower of Hanoi"},"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=\"#what-is-the-tower-of-hanoi\">What is the Tower of Hanoi?<\/a><\/li><li><a href=\"#problem-statement-program-for-tower-of-hanoi-algorithm\">Problem Statement: Program for Tower of Hanoi Algorithm<\/a><\/li><li><a href=\"#recursive-approach---\">Recursive Approach<strong><br><\/strong><\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code-for-recursive-approach\">C++ Code for Recursive Approach<\/a><\/li><li><a href=\"#java-code-for-recursive-approach-\">Java Code for Recursive Approach <\/a><\/li><li><a href=\"#python-code-for-recursive-approach-\">Python Code for Recursive Approach <\/a><\/li><\/ul><li><a href=\"#frequently-asked-questions\">Frequently Asked Questions<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-what-are-the-minimum-moves-to-solve-the-tower-of-hanoi-problem\">Q.1: What are the minimum moves to solve the Tower of Hanoi problem?<\/a><\/li><li><a href=\"#q2-what-is-the-space-complexity-of-the-tower-of-hanoi\">Q.2: What is the space complexity of the Tower of Hanoi?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"what-is-the-tower-of-hanoi\">What is the Tower of Hanoi?<\/h2>\n\n\n\n<p>The <strong>Tower of Hanoi <\/strong>is a mathematical puzzle. It consists of <strong>three rods<\/strong> and <strong>N<\/strong> disks. The task is to move all <strong>disks<\/strong> to another <strong>rod <\/strong>following <strong>certain rules<\/strong>:<\/p>\n\n\n\n<ol><li>Only one disk can be moved at a time.<\/li><li>Only the uppermost disk can be moved from one stack to the top of another stack or to an empty rod.<\/li><li>Larger disks cannot be placed on top of smaller disks.<\/li><\/ol>\n\n\n\n<h2 id=\"problem-statement-program-for-tower-of-hanoi-algorithm\">Problem Statement: Program for Tower of Hanoi Algorithm<\/h2>\n\n\n\n<p>A diagrammatic illustration of the <strong>Tower of Hanoi:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3097 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\/10\/Image-2-5.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-5.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-5-300x146.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-5-768x375.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-5-380x186.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-5-550x269.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-5-800x391.png 800w\" ><\/figure>\n\n\n\n<p><strong>Image Source &#8211; Google images<\/strong><\/p>\n\n\n\n<p><strong>The result is :<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3098 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\/10\/Image-1-6.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-6.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-6-300x146.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-6-768x375.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-6-380x186.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-6-550x269.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-6-800x391.png 800w\" ><\/figure>\n\n\n\n<p><strong>Image Source &#8211; Google Images.<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3099 pk-lazyload\"  width=\"701\"  height=\"235\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 701px) 100vw, 701px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-1024x344.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-1024x344.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-300x101.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-768x258.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-380x128.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-550x185.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-800x269.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1-1160x390.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-5-1.png 1489w\" ><\/figure>\n\n\n\n<h2 id=\"recursive-approach---\"><span id=\"recursive-approach\">Recursive Approach<strong><br><\/strong><\/span><\/h2>\n\n\n\n<p>The idea is to use a recursive approach to solve this problem.<br>Let us try to solve the problem for <strong>N = 2<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"Tower of Hanoi Recursive\"  class=\"wp-image-3140 pk-lazyload\"  data-pk-sizes=\"auto\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/image-4.gif\" ><\/figure>\n\n\n\n<p>So, one disk is moved from <strong>rod 1<\/strong> to <strong>rod 3<\/strong>. Then the second disk is moved from <strong>rod 1 <\/strong>to <strong>rod 2<\/strong> and finally, the first disk is moved again back to <strong>rod 2<\/strong>.<\/p>\n\n\n\n<p>Similarly, the problem can be solved recursively for <strong>N = 3<\/strong>.<strong> <\/strong>Observe the below example.<\/p>\n\n\n\n<p>The minimum number of moves to solve the Tower of Hanoi problem is <strong>2^N &#8211; 1<\/strong>, where N is the number of disks.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"Tower Of Hanoi Example\"  class=\"wp-image-3141 pk-lazyload\"  data-pk-sizes=\"auto\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/image-3-1.gif\" ><figcaption>Tower Of Hanoi Example<\/figcaption><\/figure>\n\n\n\n<p><strong>Dry Run of the above illustration &#8211;<\/strong><\/p>\n\n\n\n<ul><li>Move disc 1 from tower A to tower B.<\/li><li>Move disc 2 from tower A to tower C.&nbsp;<\/li><li>Move disc 1 from tower B to tower C.<\/li><li>Move Disc 3 from tower A to tower B.<\/li><li>Move Disc 1 from tower C to tower A.<\/li><li>Move Disc 2 from tower C to tower B.<\/li><li>Move Disc 1 from tower A to tower B.<\/li><\/ul>\n\n\n\n<p><strong>Algorithm<\/strong><\/p>\n\n\n\n<ul><li>Let us consider a recursive function that takes the following argument <strong>N,<\/strong> the number of <strong>disks<\/strong>, <strong>to_Rod<\/strong>, which indicates the rod which is moved to, <strong>from_rod<\/strong>, denoting the rod from which rod is removed, and <strong>aux_rod<\/strong>, denoting the rod which is used for transferring rods from <strong>from_rod<\/strong> to <strong>to_rod<\/strong>.<\/li><li>The base case is for N = 1. Move it from source to destination, i.e. <strong>from_rod <\/strong>to <strong>to_rod.<\/strong><\/li><li>Solve the problem recursively by moving disk 1, 2, 3,&#8230;, N &#8211; 1 i.e. <strong>from_rod <\/strong>to <strong>aux_rod <\/strong>&nbsp;by recursively calling the function on (<strong>N &#8211; 1<\/strong>, <strong>from_rod, aux_rod, to_rod)<\/strong>.<\/li><li>Now, since the top <strong>N &#8211; 1<\/strong> disks have been removed from <strong>from_rod<\/strong>, move the last disk from <strong>from_rod <\/strong>to <strong>to_rod<\/strong>.<\/li><li>Similarly, again remove the top <strong>N &#8211; 1<\/strong> disk from <strong>aux_rod<\/strong> to <strong>to_rod<\/strong> and recursively call the function on <strong>(N &#8211; 1, aux_rod, to_rod, from_rod)<\/strong><\/li><li>Repeat the above steps until it reaches the base case.<\/li><\/ul>\n\n\n\n<h3 id=\"c-code-for-recursive-approach\">C++ Code for Recursive Approach<\/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=\"\">void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)\n{\n    if (n == 1)\n    {\n        cout &lt;&lt; \"Move disk 1 from rod \" &lt;&lt; from_rod &lt;&lt;\n                            \" to rod \" &lt;&lt; to_rod&lt;&lt;endl;\n        return;\n    }\n    towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);\n    cout &lt;&lt; \"Move disk \" &lt;&lt; n &lt;&lt; \" from rod \" &lt;&lt; from_rod &lt;&lt;\n                                \" to rod \" &lt;&lt; to_rod &lt;&lt; endl;\n    towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);\n}\nsolve(){\n      TowerOfHanoi(n, 'A', 'C', 'B');\n}<\/pre>\n\n\n\n<h3 id=\"java-code-for-recursive-approach-\"><span id=\"java-code-for-recursive-approach\">Java Code for Recursive Approach <\/span><\/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=\"\">static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)\n{\n    if (n == 1)\n    {\n        System.out.println(\"Move disk 1 from rod \"+\n                           from_rod+\" to rod \"+to_rod);\n        return;\n    }\n    towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);\n    System.out.println(\"Move disk \"+ n + \" from rod \" +\n                       from_rod +\" to rod \" + to_rod );\n    towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);\n}\n \nsolve(){\n   TowerOfHanoi(n, 'A', 'C', 'B')\n \n}<\/pre>\n\n\n\n<h3 id=\"python-code-for-recursive-approach-\"><span id=\"python-code-for-recursive-approach\">Python Code for Recursive Approach <\/span><\/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=\"\">def TowerOfHanoi(n , from_rod, to_rod, aux_rod):\n    if n == 1:\n        print(\"Move disk 1 from rod\",from_rod,\"to rod\",to_rod)\n        return\n    TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)\n    print(\"Move disk\",n,\"from rod\",from_rod,\"to rod\",to_rod)\n    TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)\n \ndef solve():\n      TowerOfHanoi(n, 'A', 'C', 'B');<\/pre>\n\n\n\n<p><strong>Time Complexity:<\/strong> O(2^N) where N is the number of disks.<br><strong>Space Complexity:<\/strong> O(N), as the disks, take up the recursive stack space.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide\"\/>\n\n\n\n<h2 id=\"frequently-asked-questions\">Frequently Asked Questions<\/h2>\n\n\n\n<h3 id=\"q1-what-are-the-minimum-moves-to-solve-the-tower-of-hanoi-problem\"><span id=\"q-1-what-are-the-minimum-moves-to-solve-the-tower-of-hanoi-problem\">Q.1: What are the minimum moves to solve the Tower of Hanoi problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans:<\/strong> The minimum moves required is 2^N &#8211; 1 to move all disks from Source rod A to destination rod B while following the rules.<\/p>\n\n\n\n<h3 id=\"q2-what-is-the-space-complexity-of-the-tower-of-hanoi\"><span id=\"q-2-what-is-the-space-complexity-of-the-tower-of-hanoi\">Q.2: What is the space complexity of the Tower of Hanoi?<\/span><\/h3>\n\n\n\n<p>Ans: The space complexity is O(N) since, for each recursion, the disks take up N &#8211; 1 recursive stack space.<\/p>\n","protected":false},"excerpt":{"rendered":"What is the Tower of Hanoi? The Tower of Hanoi is a mathematical puzzle. It consists of three&hellip;\n","protected":false},"author":5,"featured_media":3143,"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":[480],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/2913"}],"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=2913"}],"version-history":[{"count":5,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/2913\/revisions"}],"predecessor-version":[{"id":20073,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/2913\/revisions\/20073"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/3143"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=2913"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=2913"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=2913"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}