The Towers of Hanoi 0 1 0

The Towers of Hanoi
Dr. Liam Naughton
1
The Towers of Hanoi
The Towers of Hanoi is an interesting recursion based puzzle. The puzzle consists of 8
disks initially stacked on one of three pegs in decreasing size as shown in the picture.
The aim of the puzzle is to transfer the entire tower to one of the other pegs by moving
only a single disk at a time and never placing a larger disk on top of a smaller one. The
best solution to the puzzle is the solution which uses as few moves as possible. At first
glance it is not obvious that this puzzle can be solved at all. In order to get a handle on
the recursive nature of this puzzle let’s start small.
• If there is only one disk then we only need one move.
Step
0
Step
1
• If there are two disks then we need three moves.
0
Step
1
Step
1
Step
2
Step
3
• If there are three disks then we need seven moves.
Step
0
Step
1
Step
2
Step
3
Step
4
Step
5
Step
6
2
7
Step
What about a tower with four disks? Analysis of the three above solutions yields a
clue. When solving the puzzle with three disks the solution is to transfer the top two
disks to the middle peg, then move the third, and finally transfer the two pegs onto it.
In other words, top solve the problem with three pegs we
• Move the tower of two disks to the middle peg - 3 moves.
• Move the third peg - 1 move.
• Move the tower of two disks onto the third disk - 3 moves.
This gives us a clue as to how to solve the problem with any number, n, of disks. We
first move the tower of n − 1 disks to the middle peg, then move the nth disk and then
move the tower with n − 1 disks on top of the nth disk. If Tn is the number of moves
required to solve the puzzle with n disks then
Tn = Tn−1 + 1 + Tn−1
= 2Tn−1 + 1
This recurrence relation describes the number of moves needed to solve the Towers of
Hanoi puzzle with n disks. We’d now like to solve this recurrence relation, that is, we’d
like to find a general formula for the number of moves required to solve the puzzle with
n disks which doesn’t require us to solve the puzzle on n − 1 disks first. To get a feel for
a possible solution we’ll make a table of the first few values of Tn .
Tn
n
0
0
1
2(0) + 1 = 1
2
2(1) + 1 = 3
2(3) + 1 = 7
3
4
2(7) + 1 = 15
5
2(15) + 1 = 31
6
2(31) + 1 = 63
7
2(63) + 1 = 127
8 2(127) + 1 = 255
It looks as if the values of Tn are one less than 2n . In other words it would appear that
Tn = 2n − 1.
Theorem 1. The general solution to the recurrence relation Tn = 2Tn−1 + 1 is given by
Tn = 2n − 1.
3
Proof. The proof proceeds by induction. If you are unfamiliar with this technique you
cans kip to the next section.
• For the base case n = 0 we have
T0 = 20 − 1 = 1 − 1 = 0.
• Suppose the statement is true for n = k i.e.
Tk = 2k − 1.
• Now for n = k + 1 we have
Tk+1 =
=
=
=
4
2Tk + 1
2(2k − 1) + 1
2k+1 − 2 + 1
2k+1 − 1