算法练习——汉诺塔问题

汉诺塔问题介绍:
在印度,有这么一个古老的传说:在世界中心贝拿勒斯(在印度北部)的圣庙里,一块黄铜板上插着三根宝石针。印度教的主神梵天在创造世界的时候,在其中一根针上从下到上地穿好了由大到小的64片金片,这就是所谓的汉诺塔。不论白天黑夜,总有一个僧侣在按照下面的法则移动这些金片,一次只移动一片,不管在哪根针上,小片必在大片上面。当所有的金片都从梵天穿好的那根针上移到另外一概针上时,世界就将在一声霹雳中消灭,梵塔、庙宇和众生都将同归于尽。

问题分析:

当n=1时:A  >  C

当n=2时:A  >  B

                  A  >  C

                  B  >  C

实现这个算法可以简单分为三个步骤(递归思想):

    (1)     把n-1个盘子由A 移到 B;

    (2)     把第n个盘子由 A移到 C;

    (3)     把n-1个盘子由B 移到 C;

实现代码:

package com.suanfa.test;

import java.util.Scanner;
/*汉诺塔问题*/
public class HanoiTower {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        while (true) {
            System.out.print("请输入要移动的盘子个数:");
            Scanner sc=new Scanner(System.in);
            int n=sc.nextInt();
            hanoi(n,'A','B','C');
        }
    }
    public static void hanoi(int n,char A,char B,char C) {
        if (n==1) {
            System.out.println("盘子1从"+A+"到"+C);
        }
        else {
            hanoi(n-1,A,C,B);
            System.out.println("盘子"+n+"从"+A+"到"+C);
            hanoi(n-1,B,A,C);
        }
    }

}

 

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

余额充值