Friday 19 July 2013

05. Write a C++ program that uses a recursive function for solving Towers of Hanoi problem.

What is Towers of Hanoi Problem:
             Towers of Hanoi Problem 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.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk may be moved at a time.
  2. Each move consists of taking the disk from one of the stacks and placing it on top of another stack.
  3. No disk may be placed on top of a smaller disk. (-Source from WIKIPEDIA)

                                                             A               C               B
Let 'A', 'B', 'C' are three rods and; 'n' is the number of disks on the starting rod,
         The minimum number of moves required to solve a Tower of Hanoi puzzle is count = 2n - 1.

Solution
#include<iostream>
int count1;                            //Global variables are by default initialized to '0' for int type
void hanoi(char A,char B, char C, int n)
{
    if(n>1)
    {
        hanoi(A,C,B,n-1);
        hanoi(A,B,C,1);
        hanoi(C,B,A,n-1);
    }
    else
    {
    cout<<"\n disc moved from '"<<A<<"' to '"<<B";
    count1++;
    }
}
int main()
{
    int n;
    cout<<"enter stack height :";
    cin>>n;
    hanoi('A','B','C',n);                 //we assume that 'A' is the starting rod consisting of rod of disks
    cout<<"\n number of changes done are : "<<count1;
    return 0;
}

No comments:

Post a Comment