Tower of Hanoi
The Animation for the Tower of Hanoi is:
A total of 2n-1 moves are made.
The code for it is:-
#include <iostream>
using namespace std;
//For Tower of Hanoi
///If N=ODD make first move from A to C;
///If N if Even then make first move from A to B;
void TowerOfHanoi(int N,char source,char aux,char destn)
{
if(N==1)
{
cout<<source<<"-->"<<destn<<endl;;
return;
}
TowerOfHanoi(N-1,source,destn,aux);
cout<<source<<"-->"<<destn<<endl;;
TowerOfHanoi(N-1,aux,source,destn);
}
int main()
{
char source,destn,aux;
int N;
cout<<"Enter the number of discs";
cin>>N;
if(N%2==0)
{
TowerOfHanoi(N,'A','C','B');
}else
if(N%2!=0)
{
TowerOfHanoi(N,'A','B','C');
}
return 0;
}
For N=2 the solution will be:
A-->C
A-->B
C-->B
A total of 2n-1 moves are made.
The code for it is:-
#include <iostream>
using namespace std;
//For Tower of Hanoi
///If N=ODD make first move from A to C;
///If N if Even then make first move from A to B;
void TowerOfHanoi(int N,char source,char aux,char destn)
{
if(N==1)
{
cout<<source<<"-->"<<destn<<endl;;
return;
}
TowerOfHanoi(N-1,source,destn,aux);
TowerOfHanoi(N-1,aux,source,destn);
}
int main()
{
char source,destn,aux;
int N;
cout<<"Enter the number of discs";
cin>>N;
if(N%2==0)
{
TowerOfHanoi(N,'A','C','B');
}else
if(N%2!=0)
{
TowerOfHanoi(N,'A','B','C');
}
return 0;
}
For N=2 the solution will be:
A-->C
A-->B
C-->B
Comments
Post a Comment