Search This Blog

C Program to Solve Tower of Hanoi Puzzle

This is a c program to solve towers of Hanoi puzzle problem. This simple c program give solution for tower of Hanoi problem with any number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of Brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods. initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules. The rules of towers of Hanoi puzzle are:

  1. Only one disk can be taken at a time.
  2. It is not allowed to take any disk other the topmost one from a tower.
  3. Never place a larger disk on top of a smaller one.
  4. Place a disk nowhere else other than on tower.

The c program here displays the optimal solution for towers of Hanoi problem. You can enter the number of disks when you start. The program lists an optimal number of moves to solve the tower of Hanoi puzzle. The program displays all the moves in the order. The solution is always optimal. For a 3 disks puzzle, the optimal number of moves is 7. This c program uses a recursive function to find the solution of tower of Hanoi puzzle. The program is as follows.


#include<stdio.h>

void moveTopN(int n, int a, int b, int c)
//to Move top n disk from tower a to tower c
//Uses tower b for swapping
{
if(n>=1)
    {
    moveTopN(n-1,a,c,b);
    printf("\nMove top disk from tower %d to tower %d",a,c);
    moveTopN(n-1,b,a,c);
    }
}

void main()
{
    int n;
    printf("Enter number of disks");
    scanf("%d",&n);
    moveTopN(n,1,2,3);
}

The above c program first reads the number of disks in the tower of Hanoi Puzzle. Then it displays the optimal moves to solve the puzzle.

No comments: