蓝桥杯7——汉诺塔问题

在这里插入图片描述

解题思路

分析汉诺塔的转移过程,发现汉诺塔问题可以通过分治法分解为许多的小问题,例如A柱上的圆盘个数为n,汉诺塔问题可以分解为:
①:把n-1个A柱子的圆盘通过C柱转移到B柱子上
②:把第n个圆盘从A柱子转移到C柱上
③:把n-2个圆盘从B柱子转移到C柱子上
其中的③,又可以分解为:
①:把n-1个B柱子的圆盘通到A柱子上
②:把第n-1个圆盘由B移到C
③:把n-2个圆盘由A移到C
这样我们递归就明了了。

解题代码

#include<bits/stdc++.h>
using namespace std;
int step=0;
void hannuo(int n,int m,string a,string b,string c ){
//把n个圆盘从a柱通过b柱转移到c柱上
    if(n==1){
        step++;
        if(step==m){
            cout<<"#"<<n<<": "<<a<<"->"<<c<<endl;
        }
    }else{
        hannuo(n-1,m,"A","C","B");
        step++;
        if(step==m){
            cout<<"#"<<n<<": "<<a<<"->"<<c<<endl;
            //完成一次hannuo()函数之后,依据条件进行输出
        }
        hannuo(n-1,m,"B","A","C");
    }
} 
int main(){
    int M,N;
    cin>>N>>M;
    hannuo(N,M,"A","B","C");
    cout<<step;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
汉诺塔问题是一个经典的问题,源于印度一个古老传说。问题是将一根柱子上的64片黄金圆盘按照大小顺序重新摆放到另一根柱子上,且在任何时候,小圆盘上不能放大圆盘,且一次只能移动一个圆盘。 汉诺塔问题的循环算法可以使用迭代的方式来解决。下面是一个示例代码: ```cpp #include <iostream> #include <stack> #include <string> using namespace std; void hanoiTowerIterative(int N, string from, string to, string help) { stack<int> s1, s2, s3; int moves = (1 << N) - 1; for (int i = N; i > 0; i--) { s1.push(i); } if (N % 2 == 0) { swap(s2, s3); } for (int i = 1; i <= moves; i++) { if (i % 3 == 1) { if (s1.empty() || (!s2.empty() && s2.top() < s1.top())) { cout << "Move " << s2.top() << " from " << to << " to " << from << endl; s1.push(s2.top()); s2.pop(); } else { cout << "Move " << s1.top() << " from " << from << " to " << to << endl; s2.push(s1.top()); s1.pop(); } } else if (i % 3 == 2) { if (s1.empty() || (!s3.empty() && s3.top() < s1.top())) { cout << "Move " << s3.top() << " from " << help << " to " << from << endl; s1.push(s3.top()); s3.pop(); } else { cout << "Move " << s1.top() << " from " << from << " to " << help << endl; s3.push(s1.top()); s1.pop(); } } else { if (s2.empty() || (!s3.empty() && s3.top() < s2.top())) { cout << "Move " << s3.top() << " from " << help << " to " << to << endl; s2.push(s3.top()); s3.pop(); } else { cout << "Move " << s2.top() << " from " << to << " to " << help << endl; s3.push(s2.top()); s2.pop(); } } } } int main() { hanoiTowerIterative(3, "A", "B", "C"); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值