Tower of Hanoi problem (recursive) - Learning Algorithm

problem

Ancient a tower, the tower has three seats A, B, C, A has the disc plate 64, the plate sizes, the lower large, the small, there is a plate 64 which wants monk from A, move Block C, but each time only allowed to move a tray, and during the movement, the seat 3 remains below the market, on the small cap, during movement of the seat B may be utilized, the output of the step required to move
Here Insert Picture Description
ideas:
B is a plate with a relay, to move the C drive, on the first moving plate a to B, C for the transit time to the last for the transit of a to C to move the plate, is formed recursively

Code:

void Hanoi(int n,char A,char B,char C)
//将A座上的n个盘子,以B为中转,移动到C座
{
if(n==1){//只需移动一个盘子
cout<<A<<"->"<<C<<endl;
//直接将盘子从A移动到C
return ;//递归终止
 }
Hanoi(n-1,A,C,B);//先将n-1个盘子从A移动到B
 cout<<A<<"->"<<C<<endl;
Hanoi(n-1,B,A,C);//最后将n-1个盘子从B移动到C
 return;
 }
int main()
{
 int n;
 cin>>n;//输入盘子数目
 Hanoi(n,'A','B','C');
 return 0;
}
Published 79 original articles · won praise 133 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_45822638/article/details/105027508