汉诺塔——栈的运用

思路

将N个盘子从A运到C 要解决将N-1个盘子从A运到B 再将剩下的一个盘子从A运到C

之后问题变成:将n-1个盘子从B运到C 那么需要将n-2 个盘子从B 运到A 将剩下的盘子从B运到C 再将n-2个盘子从A 运到C 依次递归 

出界条件为n==1;

#include <iostream>
using namespace std;
void Hanoi(int x, char a, char b, char c)
{
    if (x == 1)
        cout << " move " << a << " to " << c << endl;
    else
    {
        Hanoi(x - 1, a, c, b);
        cout << " move " << a << " to " << b << endl;
        Hanoi(x - 1, b, a, c);
    }
}
int main()
{
    Hanoi(3, 'A', 'B', 'C');
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值