Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests - Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests -

Tower of Hanoi

The Tower of Hanoi is a mathematical problem formed of three towers. The purpose of the puzzle is to push the whole stack to another bar. While moving the stacks, we need to obey some simple rules: we can only remove one disk at a time.

Tower of Hanoi

Table of Contents

Understand the Tower of Hanoi Puzzle

To understand this puzzle, we are using the image as an example. The below image represents the setup of the tower of the Hanoi puzzle.

Tower of Hanoi 1

In the above image, we have three towers, and one of the towers is loaded with many discs. The disc which has the greatest diameter is at the bottom, and the disc which has the smallest diameter is placed at the top. The purpose of this game is to move all discs to the destination tower without changing their ordering.

There are a few important factors to consider. To solve this puzzle, you can only shift one disc at a time. Moreover, you are not allowed to put a bigger disc on top in any situation. That means the placement should remain the same as we have seen in the first tower. We need to move the discs without disturbing the sequence.

Tower of Hanoi 3

Guidelines of Tower of Hanoi Puzzle

The Tower of Hanoi puzzle is cracked by utilising a bunch of directions, and they are as follows:

  • We are allowed to move only one disc at a time.
  • We can only transfer the top disc of one stack to another bar which is empty.
  • We cannot place the larger disc on the smaller disc.

The number of alternative moves can be used to estimate the complexity. The least moves required to decode the Tower of Hanoi puzzle with n discs are 2n-1.

Coding Implementation of Tower of Hanoi Solution

#include<stdio.h>

#include<conio.h>

void TOH(int n, char origin, char destination, char mid_t){

if(n==0){

return 0;

}

TOH(n-1,origin, mid_t,destination);

printf(“\n Move disc %d from tower %c to tower %c”,n, origin, destination);

TOH(n-1, mid_t, destination,origin);

}

int main()

{

TOH(4, ‘A’,’B’,’C’);

return 0;

}

Output:

The console conveys 15 ring movements to get the final resolution.

Tower of Hanoi 4