Showing posts with label disks. Show all posts
Showing posts with label disks. Show all posts

Saturday, 12 October 2013

Towers of Hanoi Using Stack (Recursive Solution)

(The problem is moving a collection of N disks of decreasing size from one pillar to another.The movement of the disks is restricted by the following rules:
Rule1: Only 1 disk could be moved at a time.
Rule2: No larger disk could ever reside on a pillar on top of a smaller disk.
Rule3: A 3rd pillar can be used as an intermediate to store one or more disks,while the disks are moved from source to destination )

Let N represent the number of disks
Step1: If N=1,move the disk from A to C.
Step2:
  1. If N=2,move the 1st disk from A to B,
  2. Then move the 2nd disk from A to C,
  3. Then move the 1st disk in B to C.
Step3: If N=3,repeat step2,to move the first two disks from A to B using C as intermediate.
Then move 3rd disk from A to C.Then repeat the step2 to move 2disks from B to C using A as intermediate

In general,to move N disks,apply recursive technique to move (N-1) disks from A to B with C as an intermediate.Then move the Nth disk from A to C.Then again apply the recursive technique to move (N-1) from B to C using A as intermediate.