Towers of Hanoi is one of the example illustrating the recursion technique.The problem is moving a collection of N disks of decreasing size from one pillar to another pillar. the movement of the disk is restricted by the following rules.
- Only one disk could be moved at a time.
- No larger disk could ever reside on a pillar on top of a smaller disk.
- A 3rd pillar could be used as an intermediate to store one or more disks, while they ere being moved from source to destination.
Recursive solution:
N ➜ Represents the number of disk
- If N=1 move the disk from A to C.
- If N=2 move the 1st disk from A to B .then move the 2nd disk from A to C then move 1st disk from B to C.
- If N=3 Repeat the step 2 to move the first 2 disks from A to B using C as intermediate.Then 3rd disk is moved from A to C.then repeat the step2 to move 2 disk from B to C using A as intermediate.
EXAMPLE:
Towers of Hanoi problem for 2 disk.
No comments:
Post a Comment