Thursday, April 21, 2011

Recursive Solution for Tower of Hanoi

The Tower of Hanoi or Towers of Hanoi , also called the Tower of Brahma or Towers of Brahma, is a mathematical game or 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 in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
Tower of Hanoi
The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
  • Only one disk may 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 disk may be placed on top of a smaller disk.
Source:- wikipedia.org
Solution
/////////////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
void solveTOH(int x,int y, int z);
int main(){
int input;
printf("enter the number of pegs:");
scanf("%d",&input);
printf("goint to solve %d number of disks\n\n",input);
solveTOH(input,1,3);
return 0;
}
void solveTOH(int noOfDisks,int initial,int toTransfer)     // initial: transfer disks from which tower
//toTransfer: transfer disks to which tower
{
int temp;
if(initial!=3&&toTransfer!=3){
temp=3;
}else if(initial!=2&&toTransfer!=2){
temp=2;
}else{
temp=1;
}
if(noOfDisks!=1){
solveTOH(noOfDisks-1,initial,temp);
printf("moving %d from %d----->%d\n",noOfDisks,initial,toTransfer);
solveTOH(noOfDisks-1,temp,toTransfer);
}else{
printf("moving %d from %d----->%d\n",noOfDisks,initial,toTransfer);
}
}