Tower of Hanoi code

Tower of Hanoi is a Mathematical Game. There are 3 pegs (Rods) and number of discs, each of different size, which can be inserted into the rods. All discs are initially inserted into one rod in increasing order (smallest at the top and largest disc at the bottom). You have to move all the discs from source rod to Destination rod, with below 2 restrictions:

  1. Only one disc can be moved at a time.
  2. You cannot place a larger disc on the top of a smaller disc ever.
For example: If the Pegs are named as S, D & E (Source, Destination & Extra) and there are 4 discs, the initial state will be


And final state will be:



Write a function that accept the names of three rods (S, D & E) and the number of discs, and print the movement of discs between the rods such that all the rods are moved from S to D. The signature of the function will be

/* The three char represents the characters representing three rods
 * and n is the number of discs (initially in s)
 */
 void towerOfHanoi(char s, char d, char e, int n)

Solution:


The solution to this problem can be easily thought in a recursive approach. The Problem:

Move n Discs from S to D using E

Can be solved in 3 steps:

Step-1:  Move n-1 discs from S to E using D
Step-2:  Move the nth disc from S to E
Step-3:  Move n-1 discs from E to D using S

If you notice, the Step-1 & Step-3 are recursive calls to the same function. Hence the code of the function will be:

     void towerOfHanoi(char s, char d, char e, unsigned int n)
     {
          if(n > 0)
          {
               towerOfHanoi(s, e, d, n-1);
               printf("Move Disk-%d FROM %c TO %c\n", n, s, d);
               towerOfHanoi(e, d, s, n-1);
          }
     }

If we run this Call this function for 3 discs (n=3) like below

      towerOfHanoi('s', 'd', 'e',3);

Then the output will be

Move Disk-1 FROM s TO d
Move Disk-2 FROM s TO e
Move Disk-1 FROM d TO e
Move Disk-3 FROM s TO d
Move Disk-1 FROM e TO s
Move Disk-2 FROM e TO d
Move Disk-1 FROM s TO d

The actual movement of the disks will be as shown below:

   

0 Comments

Leave a comment