Friday, September 16, 2016

Tower Of Hanoi

Tags


The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower,[1] and sometimes pluralized) 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 conicalshape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks
C++ Program To Solve The Above Problem is Given Below:
//program to solve the hanoi problem
#include<iostream>
using namespace std;
void toi(int n,char tower1,char tower2,char tower3)
{
if(n==1)
{
cout<<"Shift Top Disk From Tower"<<tower1<<"to Tower"<<tower2<<"\n";
return;
}
toi(n-1,tower1,tower3,tower2);
cout<<"Shift Top Disk From Tower"<<tower1<<"To Tower"<<tower2<<"\n";
toi(n-1,tower3,tower2,tower1);
}
main()
{ int disk;
cout<<"ENTER THE NO OF DISKS";
cin>>disk;
if(disk<1)
{
cout<<"PLEASE ENTER MORE DISKS";
exit (0);
}
toi(disk,'1','2','3');
cout<<disk<<"DISKS ARE SHIFTED FROM TOWER 1 TO TOWER 2";
}
ALSO SEE NUMBER PATTERN CLICK HERE