Tower of Hanoi is a famous mathematical puzzle. It was proposed by Edouard Lucas in 1883. The objective of this puzzle is to move stack of n disks from one rod to another considering the following rules:
1) Only one disk can be moved at a time.
2) A bigger disk can not be placed on the top of a smaller disk.
3) Only the topmost disk can be moved from the stack.
The Tower of Hanoi problem takes minimum (2^n)-1 moves to solve.
TOWER OF HANOI WITH ONE DISK
TOWER OF HANOI WITH TWO DISKS
TOWER OF HANOI WITH THREE DISKS
PROGRAM
//Program to solve Tower of Hanoi Problem
#include <iostream>
using namespace std;
void toh(int n, char from, char to, char aux)
{
if(n==1)
{
cout<<"\nMOVE DISK FROM TOWER "<<from<<" TO TOWER "<<to;
}
else
{
toh(n-1,from,aux,to);
cout<<"\nMOVE DISK FROM TOWER "<<from<<" TO TOWER "<<to;
toh(n-1,aux,to,from);
}
}
int main()
{
int n;
cout<<"ENTER NUMBER OF DISKS: ";
cin>>n;
toh(n,'A','C','B');
return 0;
}
OUTPUT