Site icon Study Algorithms

Discuss the Tower Of Hanoi puzzle

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:-

Algorithm

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.

Exit mobile version