You are on page 1of 2

DSA ASSIGNMENT

Muhammad Haider Ali Sohail


18-SE-72

TOWERS OF HANOI

EXPLANATION

There are three towers given and one of the tower is having a stack of disks and increasing size of disk
from top to bottom .The target is to move all of the disks from tower 1 to another tower by following
the below rules :

1)1 disk can be moved only at one instant.

2)At any moment of time bigger disk cannot be placed above a small disk.

3)Each move involves taking the topmost disk from one of the towers and placing it on top of another
tower i.e. a disk is moved only if it is the topmost disk in a tower.

There canbe any number of disks given in this tower. We will solve this problem by taking some small
examples .

01 DISK:

Suppose there is only one disk given in the tower then solution is very easy . Move disk from tower 1 to
tower 3.

02- DISKS:

Assume disk -1 to be on top of disk -2 at tower 1. The goal is to move both the disks to tower 2.It can be
done by following the next steps:

 Move disk -1 from tower 1 to tower 3.


 Move disk- 2 from tower 1 to tower 2.
 At last,move disk -1 from tower 3 to tower 2.

It only takes 3 steps.

One could easily move the stack from tower 2 to another tower using the above 3 steps.
03 DISKS:

What happens if we have 3 disks in tower 1.

To move the disks to tower 2, you will need to expose disk- 3 and for it disk -1 and disk- 2 should be
moved to tower 3.

So keeping in mind the rules of the game, use the aforementioned sub-sets of 3 steps in the earlier case,
move disk -1 and disk-2 to tower 3, leaving disk -3 alone with zero disks over it.Proceed as follows:

 Using recursion move disk-3 from tower 1 to tower 3.


 Move disk -1 from tower 3 to tower 1.Then disk -2 is moved above disk -3 at tower 2.
 Game is finished by moving disk -1 from tower 1 over disk- 2 and disk-3 at tower 2.

N-DISKS:

For N disks, it takes [(2*N)-1] steps to finish the puzzle.

The task can be completed in minimum steps as follows:

 Move the first(top) N-1 disks to a temporary tower.


 Move the last(bottom) disk to the final tower.
 At last, move the N-1 disks from the temporary tower to the final tower.

ALGORITHM:

Three towers are taken with the names, ini, desti and auxi (used to move the disks).

START

Process TofHanoi(disk, ini, desti, auxi)

if disk == Null, Then

move disk from ini to desti

else

Step-1 TofHanoi(disk-1, ini, auxi, desti)

Step-2 move disk from ini to desti

Step-3 TofHanoi(disk-1, auxi, desti, ini)

End if

End Process

Exit

You might also like