Uploaded by artixman125

Tower of Hanoi (1)

advertisement
Tower of Hanoi
Presented By:
Sohaib Ahmed and Shumail Qaiser
Description of Problem:

Tower of Hanoi or Towers of Hanoi is a mathematical game or
puzzle.It consists of three rods and number of disks of
different sizes which can slide onto any rod.

The puzzle starts with disks on a neat stack placed in ascending order of
disks,the smallest at top as shown below:
Objective of Tower of Hanoi:

The objective is to move all of the disks onto some other stack
in a same order as if they were in the beginning.
Rules for Tower of Hanoi puzzle:

Only one disk can be moved at a time.

Each move consists of taking the upper disk from one of the
rods and sliding it on another rod,on top of disks that may
already be present on that rod.

No disk can be placed on top of smaller disk than itself.
Time and Space Complexity

In tower of hanoi, a recursion tree is formed which makes the time
complexity exponential ,O(2^n)

Due to recursion calls stored on stack one after another,space
complexity is also O(2^n)
For 1 Disk
1
For 2 Disks
1
2
For 2 Disks
1
2
For 3 Disks
1
2
3
For 3 Disks
1
2
3
Algorithm Derived

The following algorithm can be derived on the above observations:

Move ‘n-1’ disks from source to auxiliary rod

Move the ‘n’ disk from source to destination

Move the ‘n-1’ disks from auxiliary rod to destination
Main Code
towerOfHanoi function
TOH(3,A,B,
C)
TOH(2,B,A,C)
DISK 3 :
A->C
TOH(2,A,C,B)
DISK 2 :
A->B
TOH(1,A,B,C)
DISK 2 :
B->C
TOH(1,C,A,B)
TOH(1,B,C,A)
TOH(1,A,B,C)
DISK 1 :
C->B
DISK 1 :
B->A
DISK 1 :
A->C
DISK 1 :
A->C
TOH
(0,A,C,
B)
RETURN
TOH
(0,B,A,
C)
TOH
(0,C,B,
A)
TOH
(0,A,C,
B)
TOH
(0,B,A,C
)
TOH
(0,C,B,A
)
TOH
(0,A,C,B
)
TOH
(0,B,A,C
)
RETURN
RETURN
RETURN
RETURN
RETURN
RETURN
RETURN
Download