Tutorialspoint
Problem
Solution
Submissions

Tower of Hanoi

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to solve the Tower of Hanoi problem for n disks. The Tower of Hanoi consists of three rods and a number of disks of different sizes. The puzzle starts with the disks stacked on one rod in order of decreasing size, with the smallest at the top. The objective is to move the entire stack to another rod, following these rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one stack and placing it on top of another stack or on an empty rod. 3) No disk may be placed on top of a smaller disk.

Example 1
  • Input: n = 2
  • Output:
    • Move disk 1 from rod A to rod B
    • Move disk 2 from rod A to rod C
    • Move disk 1 from rod B to rod C
  • Explanation:
    • Step 1: Move smallest disk from source (A) to auxiliary rod (B)
    • Step 2: Move larger disk from source (A) to destination rod (C)
    • Step 3: Move smallest disk from auxiliary (B) to destination (C)
    • Step 4: All disks moved successfully following the rules
Example 2
  • Input: n = 3
  • Output:
    • Move disk 1 from rod A to rod C
    • Move disk 2 from rod A to rod B
    • Move disk 1 from rod C to rod B
    • Move disk 3 from rod A to rod C
    • Move disk 1 from rod B to rod A
    • Move disk 2 from rod B to rod C
    • Move disk 1 from rod A to rod C
  • Explanation:
    • Step 1: Recursively move n-1 disks from source to auxiliary rod
    • Step 2: Move largest disk from source to destination rod
    • Step 3: Recursively move n-1 disks from auxiliary to destination rod
    • Step 4: Total 2^n-1 moves required for n disks
Constraints
  • 1 ≤ n ≤ 20
  • Time Complexity: O(2^n)
  • Space Complexity: O(n)
Functions / MethodsRecursionMicrosoftFacebook
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursion to solve this problem.
  • For n disks, you need 2^n - 1 moves.
  • To move n disks from source to destination using an auxiliary rod:
    • Move n-1 disks from source to auxiliary
    • Move the nth disk from source to destination
    • Move n-1 disks from auxiliary to destination

Steps to solve by this approach:

 Step 1: Define the base case (n=1): move the disk directly to destination.

 Step 2: Use recursion to solve the general case for n disks.
 Step 3: Move n-1 disks from source to auxiliary rod.
 Step 4: Move the largest disk from source to destination rod.
 Step 5: Move the n-1 disks from auxiliary rod to destination rod.
 Step 6: Print each move as it's made during the solution.

Submitted Code :