0
点赞
收藏
分享

微信扫一扫

C++---汉诺塔问题(递归)


代码

#include<iostream>
using namespace std;
static int counts=1;
void move(char src,char dest)
{
cout<<"第"<<counts<<"步: "<<src<<"------->"<<dest<<endl;
counts++;
}
// hanoi: 从src 全部移动至 dest
void hanoi(int n,char src,char medium,char dest)
{
if(n==1)
move(src,dest);
else
{
// 分为两部分 上面n-1块 最下面1块

// 先把上半部分(n-1) 从src移动至medium
hanoi(n-1,src,dest,medium);
// 再把最后一部分(1)移动至dest
move(src,dest);
// 最后再把上半部分(n-1) 从medium移动至dest
hanoi(n-1,medium,src,dest);
}
}
int main()
{
int m;
//cin>>m;
cout<<"请输入汉诺塔 层数:"<<endl;
cin>>m;
cout<<"步骤是:"<<endl;
hanoi(m,'A','B','C');

return 0;
}

C++---汉诺塔问题(递归)_C++


C++---汉诺塔问题(递归)_C++_02

C++---汉诺塔问题(递归)_程序运行_03


C++---汉诺塔问题(递归)_汉诺塔_04

程序运行界面

C++---汉诺塔问题(递归)_ios_05


举报

相关推荐

0 条评论