The document describes the Tower of Hanoi puzzle, which involves moving disks of different sizes between three pegs according to rules of only moving one disk at a time and never placing a larger disk on top of a smaller one. It provides an algorithm and recursive solution for solving the puzzle by moving disks from the source peg to the auxiliary peg and then to the destination peg. The number of minimum moves needed to solve the puzzle for n disks is 2^n - 1. For example, 4 disks requires 15 moves.
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle invented by a
French Mathematician in 1883.
The game starts by having few discs stacked in
increasing order of size. The number of discs can vary,
but there are only three pegs.
3.
Tower of Hanoi
The Objective is to transfer the entire tower to one of
the other pegs. However you can only move one disk at
a time and you can never stack a larger disk onto a
smaller disk. Try to solve it in fewest possible moves.
Tower of Hanoi
Recursive Solution for the Tower of Hanoi with
algorithm.
Let’s call the three peg Src(Source), Aux(Auxiliary) and
Dst(Destination).
Move the top N – 1 disks from the Source to Auxiliary
tower.
Move the Nth disk from Source to Destination tower.
Move the N – 1 disks from Auxiliary tower to Destination
tower. Transferring the top N – 1 disks from Source to
Auxiliary tower can again be thought of as a fresh
problem and can be solved in the same manner.
6.
Tower of Hanoi
TOWER(N,BEG, AUX, END)
1. If N = 1 then
a. Write BEG --> END
b. Return
2. [Move N-1 disks from peg BEG to peg AUX]
Call TOWER(N-1, BEG, END, AUX)
3. Write BEG --> END
4. [Move N-1 disks from peg AUX to peg END]
Call TOWER(N-1, AUX, BEG, END)
5. Return.
7.
Tower of Hanoi
ForN = 4 we get the following sequence
1. Move from Src to Aux
2. Move from Src to Dst
3. Move from Aux to Dst
4. Move from Src to Aux
5. Move from Dst to Src
6. Move from Dst to Aux
7. Move from Src to Aux
8. Move from Src to Dst
9. Move from Aux to Dst
10. Move from Aux to Src
11. Move from Dst to Src
12. Move from Aux to Dst
13. Move from Src to Aux
14. Move from Src to Dst
15. Move from Aux to Dst
8.
Tower of Hanoi
How many moves will it take to transfer n disks from
the left post to the right post?
for 1 disk it takes 1 move to transfer 1 disk from post A
to post C;
for 2 disks, it will take 3 moves: 2M + 1 = 2(1) + 1 = 3
for 3 disks, it will take 7 moves: 2M + 1 = 2(3) + 1 = 7
for 4 disks, it will take 15 moves: 2M + 1 = 2(7) + 1 = 15
for 5 disks, it will take 31 moves: 2M + 1 = 2(15) + 1 = 31
for 6 disks... ?
9.
Tower of Hanoi
Explicit Pattern
Number of Disks Number of Moves
1 1
2 3
3 7
4 15
5 31
Powers of two help reveal the pattern:
Number of Disks (n) Number of Moves
1 2^1 - 1 = 2 - 1 = 1
2 2^2 - 1 = 4 - 1 = 3
3 2^3 - 1 = 8 - 1 = 7
4 2^4 - 1 = 16 - 1 = 15
5 2^5 - 1 = 32 - 1 = 31