Tower of Hanoi - Problem
The Tower of Hanoi is a classic puzzle consisting of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with all disks stacked on one rod in ascending order of size (smallest on top).
The objective is to move the entire stack to another rod, following these rules:
- Only one disk can be moved at a time
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack
- No disk may be placed on top of a smaller disk
Given n disks, print each move in the format "Move disk from [source] to [destination]" and return the total number of moves required.
Input & Output
Example 1 — Basic Case (n=3)
$
Input:
n = 3
›
Output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
7
💡 Note:
To move 3 disks from A to C: first move disks 1,2 to B (3 moves), then disk 3 to C (1 move), then disks 1,2 from B to C (3 moves). Total: 7 moves.
Example 2 — Minimum Case (n=1)
$
Input:
n = 1
›
Output:
Move disk 1 from A to C
1
💡 Note:
Only one disk to move directly from source A to destination C. Total: 1 move.
Example 3 — Small Case (n=2)
$
Input:
n = 2
›
Output:
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
3
💡 Note:
Move disk 1 to B, disk 2 to C, then disk 1 on top of disk 2. Total: 3 moves.
Constraints
- 1 ≤ n ≤ 20
- Output each move on a separate line
- Return total number of moves as the last line
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code