The basic version of the Tower of Hanoi can be found here.
It is a twisted Tower of Hanoi problem. In which, all rules are the same with an addition of a rule:
You can not move any disk directly from the first rod to last rod i.e., If you want to move a disk from the first rod to last rod then you have to move the first rod to middle rod first and then to the last one.
- Base Case: If the number of disk is 1, then move it to the middle rod first and then move it to the last rod.
- Recursive Case: In the recursive case following steps will produce the optimal solution:(All these moves are following the rules of twisted Tower of Hanoi problem)
- We will move first n-1 disks to the last rod first.
- Then move the largest disk to the middle rod.
- Move first n-1 disks from the last rod to the first rod.
- Move the largest disk at the middle rod to the last rod.
- Move all n-1 disks from the first rode to the last rod.
Below is the implementation of the above approach:
Move disk 1 from rod A to B and then to C Move disk 2 from rod A to B Move disk 1 from rod C to B and then to A Move disk 2 from rod B to C Move disk 1 from rod A to B and then to C
T(n) = T(n-1) + 1 + T(n-1) + 1 + T(n-1) = 3 * T(n-1) + 2 where n is the number of disks.
By solving this recurrence the Time Complexity will be O(3n).
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Program for Tower of Hanoi
- Cost Based Tower of Hanoi
- Recursive Tower of Hanoi using 4 pegs / rods
- Time Complexity Analysis | Tower Of Hanoi (Recursion)
- Water Jug Problem using Memoization
- Dividing Sticks Problem
- Josephus problem | Set 1 (A O(n) Solution)
- Extended Knapsack Problem
- Word Break Problem | DP-32 | Set - 2
- 0/1 Knapsack Problem to print all possible solutions
- Difference between NP hard and NP complete problem
- Exact Cover Problem and Algorithm X | Set 1
- Program to solve the Alligation Problem
- Word Break Problem using Backtracking
- Josephus problem | Set 2 (A Simple Solution when k = 2)
- Shortest Superstring Problem | Set 2 (Using Set Cover)
- Exact Cover Problem and Algorithm X | Set 2 (Implementation with DLX)
- Maths behind number of paths in matrix problem
- Traveling Salesman Problem using Genetic Algorithm
- Maximal Clique Problem | Recursive Solution
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.