Thursday, 4 April 2013

TOWER OF HANOI

Tower of Hanoi is a very interesting mathematical problem, that invented by Edouard Lucas, in 1883.
It consists of three rods, and a number of disks of different sizes which can slide onto any rod. It consists of a pile of disks stacked one over the other such that the arrangement and movement of the disks full-fill the following rules:-
1) Only one disk movement is allowed at a time.
2) Movement of only top disk of any peg is allowed, no intermediate disk can be shifted from one peg to other.
3) A disk with larger diameter can't be placed over a disk with smaller diameter.
In other words, the disk with largest diameter in a particular peg should be at the bottom of the peg, the second largest on it, and so on.
Object:-
The object of this puzzle is to transfer all the disks from the 1st peg to the 3rd peg using an auxiliary peg.
The following gif images and videos will further help you to clarify all your doubts regarding this awesome puzzle.






Here I have a solution to this problem through my c++ programming. This problem is a very good illustration for recursive modules. I will be explaining here this recursive module, this module is for shifting n disks form beg (the beginning peg) to the end (the destination peg) using an aux (the auxiliary peg). The terminating condition of this recursive module can be easily be understood as if were to shift only one disk, then we were to just print the beg  -> end, as for a single disk we can easily slide it into the destination peg, without any restrictions.
Readers should also observe that for moving n discs, we need 2^n-1 moves.



#include<iostream.h>
#include<conio.h>
static int move_no=0;

void toh(int,char,char,char);
int main()
{
    clrscr();
    cout<<"enter the number of discs" ;
    int n;
    cin>>n;
    char beg,end,aux;
    beg='A';
    aux='B';
    end='C';
    cout<<endl<<"move number"<<"\t"<<"move"<<endl<<endl;
    toh(n,beg,aux,end);

    getch();
    return 1;
}


void toh(int n,char beg,char aux,char end)
{
    if(n==1)
    {
         move_no++;

         cout<<move_no<<"\t\t"<<beg<<"->"<<end<<endl;
         return;
    }
    toh(n-1,beg,end,aux);
    move_no++;
    cout<<move_no<<"\t\t"<<beg<<"->"<<end<<endl;
    toh(n-1,aux,beg,end);
}





output for 4 disks:-



No comments:

Post a Comment