Wednesday, June 27, 2012

Tower of Hanoi Problem(Solution in C++)


//Solving the tower of Hanoi Problem....----Feel the power of Recursion -----

#include<iostream>

using namespace std;

void solveTowerofHanoi(int n,char frompeg,char topeg, char auxpeg);

int main()
{
    int n;
    char frompeg, topeg, auxpeg;
    cout<<"Eneter the number of rings :";
    cin>>n;
    cout<<"Enter a character reprsentation for source peg :";
    cin>>frompeg;
    cout<<"Enter a character reprsentation for destination peg :";
    cin>>topeg;
    cout<<"Enter a character reprsentation for auxilliary peg :";
    cin>>auxpeg;

    cout<<"Let the 1 be the smallest ring and "<<n<<" be the largest ring, the solution is:\n";
    solveTowerofHanoi(n,frompeg,topeg,auxpeg);
    return (0);



}

void solveTowerofHanoi(int n,char frompeg,char topeg, char auxpeg)
{
    if(n == 1)
    {
        //If there is only one ring, move it directly from source peg to destination peg
        cout<<"Move ring 1 from "<<frompeg<<" to "<<topeg<<"\n";
    }
    else
    {
        //Mov n-1 pegs from source peg to auxilliary peg
        solveTowerofHanoi(n-1,frompeg,auxpeg,topeg);

        //Move the nth ring to destination peg
        cout<<"Move ring "<<n<<" from "<<frompeg<<" to "<<topeg<<"\n";

        //Now transfer the n-1 rings from auxilliary peg to the destination peg
        solveTowerofHanoi(n-1,auxpeg, topeg, frompeg);

    }


}

No comments:

Post a Comment