Towers of Hanoi problem There is a board with three pegs and

Towers of Hanoi problem: There is a board with three pegs and three disks of different sizes (see Figure 1). The goal of the game is to move the three disks from the peg where they have been placed (largest disk on the bottom, smallest disk on the top) to one of the empty pegs, subject to the following constraints: Only the top disk on a peg can be moved to another peg. A larger disk cannot be placed on top of a smaller disk. Design an algorithm to handle the Towers of Hanoi problem.

Solution

The easiest way would be to think of a recursive solution to this problem. Let\'s say there are n number of disks in L and you have to move all of them to R using above rules. So you have a function that somehow can do this. Let\'s say you are somehow able to move n - 1 of those disks to from one pole to another. Let\'s say you move top n - 1 disks from L to M, then move the bottom one that is the nth disk from L to R, now move that n-1 stack from M to R, placing them over the bottom one, Now you moved all of them from L to R which was your goal! The algorithm would be:

void towerOfHanoi(int n, char L, char R, char M)

{

    if (n == 1)

    {

        printf(\"\ Move disk 1 from rod %c to rod %c\", L, R);

        return;

    }

    towerOfHanoi(n-1, L, M, R);

    printf(\"\ Move disk %d from rod %c to rod %c\", n, L, R);

    towerOfHanoi(n-1, M, R, L);

}

int main()

{

    int n = 3; // number of disks in above case are 3

    towerOfHanoi(n, \'L\', \'R\', \'M\');

    return 0;

}

 Towers of Hanoi problem: There is a board with three pegs and three disks of different sizes (see Figure 1). The goal of the game is to move the three disks fr

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site