- Asked 2/14
- 2072 Magh · 5 marks
- 2070 Bhadra · 5 marks
TOH problem with solution for n disks
Short answer
Move n disks from source to destination using auxiliary with one disk per move and no larger on smaller. Solve recursively: move n-1 disks to auxiliary, move largest to destination, then move n-1 from auxiliary. The number of moves is 2^n - 1.
Explain TOH problem with its solution for n disks.
The problem
Tower of Hanoi has three pegs (source A, auxiliary B, destination C) and n disks of different sizes stacked on A with the largest at the bottom. Move all disks to C under these rules:
- Only one disk is moved at a time.
- Only the top disk of a peg can be moved.
- A larger disk may never be placed on a smaller one.
Recursive solution for n disks
To move n disks from A to C using B:
- Move the top n-1 disks from A to B (using C as auxiliary).
- Move the largest disk n from A to C.
- Move the n-1 disks from B to C (using A as auxiliary).
Base case: one disk is moved directly. The same idea solves the smaller problems, so it is naturally recursive.
void toh(int n, char from, char to, char aux) {
if (n == 1) { printf("Move disk 1 from %c to %c\n", from, to); return; }
toh(n - 1, from, aux, to);
printf("Move disk %d from %c to %c\n", n, from, to);
toh(n - 1, aux, to, from);
}
Number of moves
T(1) = 1 and T(n) = 2T(n-1) + 1, which gives T(n) = 2ⁿ − 1. Time complexity is O(2ⁿ).
| n | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| moves | 1 | 3 | 7 | 15 | 31 |
Example n = 3 (A to C)
| Move | Disk | From | To | Pegs after the move (A / B / C) |
|---|---|---|---|---|
| 1 | 1 | A | C | 3,2 / - / 1 |
| 2 | 2 | A | B | 3 / 2 / 1 |
| 3 | 1 | C | B | 3 / 2,1 / - |
| 4 | 3 | A | C | - / 2,1 / 3 |
| 5 | 1 | B | A | 1 / 2 / 3 |
| 6 | 2 | B | C | 1 / - / 3,2 |
| 7 | 1 | A | C | - / - / 3,2,1 |
Total 7 = 2³ − 1 moves (generated and checked with a program).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Solve TOH for 3 disks · Data Structure and Algorithm, chapter 5 · asked 2×
- Tree recursion and TOH with n disks · Data Structure and Algorithm, chapter 5
- TOH for 3 disks and recursion principle · Data Structure and Algorithm, chapter 5
- Recursion properties, Fibonacci, TOH algorithm · Data Structure and Algorithm, chapter 5
- TOH algorithm and recursion tree · Data Structure and Algorithm, chapter 5 · asked 2×
- Recursion, Fibonacci and TOH · Data Structure and Algorithm, chapter 5
- Multipath inheritance problem and solution · Object Oriented Programming, chapter 6 · asked 2×
- Dining philosophers problem and solution · Operating System, chapter 3 · asked 2×
- Galerkin and collocation solution of an ODE · Finite Element Method, chapter 4
- Data dependency problem in pipelining · Computer Organization and Architecture, chapter 4