Skip to main content

Tower of Hanoi puzzle solution using recursion complete code | total steps and print total steps with code

 Tower of Hanoi puzzle solution using recursion-


The tower of Hanoi (also called the Tower of Brahma or the Lucas tower) was invented by a French mathematician Édouard Lucas in the 19th century. It is associated with a legend of a Hindu temple where the puzzle was supposedly used to increase the mental discipline of young priests. In the legend, the young priests were given 64 gold disks stacked neatly on one of three posts. Each disk rested on a slightly larger disk. The priests' goal was to re-create the stack on a different post by moving disks, one at a time, to another post with the rule that a larger disk could never be placed on top of a smaller disk. Using mathematics, you can calculate that even when the priests found the most efficient way to solve the problem and moved the disks at a rate of one per second, it would take almost 585 billion years to finish the job. That is more than 40 times the age of the universe!

Problem Statement->

The tower of Hanoi is a famous puzzle where we have three rods and N disks. The objective of the puzzle is to move the entire stack to another rod. You are given the number of discs N. Initially, these discs are in the rod 1. You need to print all the steps of discs movement so that all the discs reach the 3rd rod. Also, you need to find the total moves.
Note: The discs are arranged such that the top disc is numbered 1 and the bottom-most disc is numbered N. Also, all the discs have different sizes and a bigger disc cannot be put on the top of a smaller disc. Refer the provided link to get a better clarity about the puzzle.

The first line of input is T denoting the number of testcases. T testcases follow. Each testcase contains a single line of input containing N.

For each testcase, print the steps and the total steps taken. Please see the example output to see the steps format.

1 <= T <= 16
1 <= N <= 16


move disk 1 from rod 1 to rod 2
move disk 2 from rod 1 to rod 3
move disk 1 from rod 2 to rod 3
move disk 1 from rod 1 to rod 3
move disk 2 from rod 1 to rod 2
move disk 1 from rod 3 to rod 2
move disk 3 from rod 1 to rod 3
move disk 1 from rod 2 to rod 1
move disk 2 from rod 2 to rod 3
move disk 1 from rod 1 to rod 3

read story about tower of Hanoi

It is strongly recommended that you should try this problem before jumping to a solution Practice Your code Here to gfg- code now


This problem can be solved by using recursion. The Tower of Hanoi is a simple problem when you solve this by using the concept of Recursion.

Before jumping to the solution let's assume that recursion is a magical function which returns your complete solution when we pass some necessary query to its parameter. This is the main concept of recursion you don't have to jump into logic initially you have to think as mention above.

now let's go-to the solution as mentioned in the problem statement we have three tower source, destination, and helper tower. We have to move the entire source tower using helper tower to destination tower.

Thinking Approach-

This is very simple if I have only one block in the source. What I will do if I have only one block in my source tower I will not use a helper tower that time I will simply move my block from source to destination and count number of step in this case i will use only one step.

Tower of Hanoi puzzle solution  using recursion code ,total step and print step
tower of Hanoi visualization 

So now i am ready to write my base case

        cout<<"move disk "<<n<<" from rod "<<s<<" to rod "<<dest<<endl;
        return step;

Let's think about the induction step
think like as I mentioned above that recursion is a magical function.
so I have written a magical function which returns the number of steps and print total step from source to destination when we pass n, source, destination and helper and the number of steps till now.

if I am standing at the top of the source what my function does my function shift the upper (n-1) block to the source to the helper tower with the help of the final destination tower and returns the total number of steps while doing it.
Then what will my intention at this point to shift the last Nth block from source to destination without the help of any third tower and increase the number of step by one and print the current step.

After doing this I will go to my final step what I have to do at this time I have to shift the rest  (n-1) block (which are currently at helper block ) form the helper tower to the final destination tower by the help of the source tower because it will empty at this time. Hopefully, you understood it if not please read twice this logic.

Now I am ready to write the induction step of my recursive function 

      cout<<"move disk "<<n<<" from rod "<<s<<" to rod "<<dest<<endl;

finally, we return the total number of steps taken by us.

This is my complete code of this problem -



Popular posts from this blog

Vaccine Distribution Codechef December Long challenge solution 2020

 Vaccine Distribution  Codechef December Long challenge solution 2020- This Problem vaccine distribution is taken from December long challenge 2020. lets read problem statement. Problem statement- Finally, a COVID vaccine is out on the market and the Chefland government has asked you to form a plan to distribute it to the public as soon as possible. There are a total of  N N  people with ages  a 1 , a 2 , … , a N a 1 , a 2 , … , a N . There is only one hospital where vaccination is done and it is only possible to vaccinate up to  D D  people per day. Anyone whose age is  ≥ 80 ≥ 80  or  ≤ 9 ≤ 9  is considered to be  at risk . On each day, you may not vaccinate both a person who is at risk and a person who is not at risk. Find the smallest number of days needed to vaccinate everyone. Input The first line of the input contains a single integer  T T  denoting the number of test cases. The description of  T T  test cases follows. The first line of each test case contains two space-separ

Codechef February long challenge solution 2021

   Codechef February  long challenge solution 2021- Hey guys Welcome Again, A small update CodeChef February  long challenge solution 2021 starting from 1st week of beb  2021 . Codechef long challenge is one of the popular contests of CodeChef you should participate in codechef Feb  long challenge.This is first contest of codechef in 2021 so good luck. And wish you happy new year. Contest link- I will post the solution after Contest.Stay tuned. About CodeChef  February  long challenge solution 2021: CodeChef Long Challenge is a 10-day monthly coding contest where you can show off your computer programming skills. The significance being - it gives you enough time to think about a problem, try different ways of attacking the problem, read the concepts etc. If you’re usually slow at solving problems and have ample time at hand, this is ideal for you. We also put in a lot of efforts in getting quality problems, w

Merge Two sorted array Without Extra Space

Problem statement-  Given two sorted arrays arr1[] and arr2[] of sizes N and M in non-decreasing order. Merge them in sorted order without using any extra space. Modify arr1 so that it contains the first N elements and modify arr2 so that it contains the last M elements.    Example 1: Input:  N = 4, arr1[] = [1 3 5 7]  M = 5, arr2[] = [0 2 6 8 9] Output:  arr1[] = [0 1 2 3] arr2[] = [5 6 7 8 9] Explanation: After merging the two  non-decreasing arrays, we get,  0 1 2 3 5 6 7 8 9.   Example 2: Input:  N = 2, arr1[] = [10, 12]  M = 3, arr2[] = [5 18 20] Output:  arr1[] = [5 10] arr2[] = [12 18 20] Explanation: After merging two sorted arrays  we get 5 10 12 18 20. Your Task: You don't need to read input or print anything. You only need to complete the function merge() that takes arr1, arr2, N and M as input parameters and modifies them in-place so that they look like the sorted merged array when concatenated. Expected Time Complexity:  O((n+m) log(n+m)) Expected Auxilliary Space: O(1