Home Theory Discuss the Tower Of Hanoi puzzle

Discuss the Tower Of Hanoi puzzle

by nikoo28
0 comments 3 minutes read

The tower of Hanoi is a mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks on one rod in ascending order of size, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, satisfying the following rules:-

  • 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 onto another rod, on top of the other disks that may already be present on that rod.
  • No large disk may be placed on top of a smaller disk.

Algorithm

  • Move the top n-1 disks from Source to Auxiliary tower.
  • Move the nth disk from Source to Destination tower.
  • Move the n-1 disks from Auxiliary tower to Destination tower.
  • Transferring the top n-1 disks from Source to Auxiliary tower can be again thought as a fresh problem and can be solved in the same manner. Once we solve the Tower Of Hanoi problem with 3 disks, we can solve it with any number of disks.
void towerOfHanoi(int n, char fromPeg, char toPeg, char auxPeg)
{
    //If only one disk, make a move and return :: base case
    if(n == 1)
    {
        printf("Move disk 1 from peg %c to peg %c ",fromPeg, toPeg);
        return;
    }
    //Move top n-1 disks from A to B, using C as auxiliary
    towerOfHanoi(n-1, fromPeg, auxPeg, toPeg);

    //Move remaining disks from A to C
    printf("\nMove disk %d from peg %c to peg %c ",n, fromPeg, toPeg);

    //Move n-1 disks from B to C using A as the auxiliary
    towerOfHanoi(n-1, auxPeg, toPeg, fromPeg);
}

Now suppose that you run the code with the calling method

towerOfHanoi(3, 'A'. 'B', 'C');

You will get an output like:-

Move disk 1 from peg A to peg B
Move disk 2 from peg A to peg C
Move disk 1 from peg B to peg C
Move disk 3 from peg A to peg B
Move disk 1 from peg C to peg A
Move disk 2 from peg C to peg B
Move disk 1 from peg A to peg B

You can download the code here.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More