汉诺塔问题

简介

有三个柱子A,B,C。A柱上有N(N>1)个直径大小不同,依小到大编号为1,2,,,n的圆盘。要求把A柱上的圆盘移到C柱上,并仍按照原来的顺序叠放,圆盘移动时遵循下列规则:

1.每次只能移动一个圆盘

2.圆盘可以插在A、B和C柱中的任何一个柱子

3.任何时刻都不能将一个较大的圆盘压在较小的圆盘之上

该问题的解法是用递归算法,算法思想如下:

if n=1,将该盘从A柱移到C柱上,递归结束。

else 将n-1个盘从A柱借助C柱移到B柱上,然后把n盘移到C柱,再把B柱上n-1个盘借助A柱移到C柱

递归代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Hanoi
//Writed by Tianze on 2020/4/21
//Copyright © 2020 Tianze All rights reserved.
using namespace std;
#include<iostream>
void hanoi(int n,char A,char B,char C){
if(n==1){
cout << "把" << n << "号盘从" << A << "柱移动到" << C << "柱" << endl;
}
else {
hanoi(n-1,A,C,B);//将n-1个盘借助C柱移到B柱
cout << "把" << n << "号盘从" << A << "柱移动到" << C << "柱" << endl;
hanoi(n-1,B,A,C);//再将B柱上n-1个盘借助A柱移到C柱
}
}
int main(){
int n,x;
cin>>n;
hanoi(n,'A','B','C');
return 0;
}

C++

写代码前顺便学习了一下C++的基本输入输出语法,在这里记录一下
首先要用using namespace std;来指定命名空间的标准库,然后使用带有cin、cout的头文件iostream。

相比于C的scanf和printf,C++的输入输出语法更为简洁方便,难怪很多ACM大佬都是用C++来写程序的,现在理解了。

1
2
cin>>x1;
cout<<"输入为"<<x1<<endl;

cout最后的endl用于自动换行

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2020-2021 Blog of Tianze

请我喝杯咖啡吧~

支付宝
微信