You are on page 1of 9

CSC 413

Algorithms & Complexity Analysis


Tower of Hanoi
Given:
stack of n disks in ascending order
Three rods
Problem:
The minimum number of moves required to move
the stack from one rod to another,
The rules:
• Only one disk can be moved at a time.
• a disk can only be moved if it is the uppermost disk on a
stack.
• No disk may be placed on top of a smaller disk.
Solution

With three disks, the puzzle can be solved in seven moves.


The minimum number of moves is 2n - 1,
wheren is the number of disks.
Tower of Hanoi Algorithm

Solve (N, Src, Aux, Dst)


If N is 0
Exit
Else solve (N-1, Src, Dst, Aux)
Move from Src to Dst
Solve(N -1 , Aux, Src, Dst)
The function calls itself repeatedly with
decreasing values of N until a terminating
condition (in our case N = 0) has been met.

For N =3 it translates into


1. Move from Src to Dst
2. Move from Src to Aux
3. Move from Dst to Aux
4. Move from Src to Dst
5. Move from Aux to Src
6. Move from Aux to Dst
7. Move from Src to Dst
Recurrence Relation for the Towers
of Hanoi

Given: T(0) = 0 N
No.Moves
T(n) = 2 T( n-1 ) +1
1 1
2 3
3 7
4 15
5 31
T(n) = 2 T( n-1 ) +1
T(n) = 2 +1
T(n) = 2 [ 2 T(n-2) + 1 ] +1
T(n) = 2 [ 2 + 1 ] +1
T(n) = 2 [ 2 [ 2 T(n-3) + 1 ]+ 1 ] +1
T(n) = 2 [ 2 [ 2 [ 2 T( n-4 ) + 1 ] + 1 ]+ 1 ] +1
T(n) = 24 T ( n-4 ) + 15
. . .

T(n) = 2k T ( n-k ) + 2k - 1
Since n is finite, k -> n. Therefore,
lim T(n) k -> n = 2n - 1

You might also like