汉诺塔问题

1. 问题陈述:

 

http://acm.hrbeu.edu.cn/index.php?act=problem&id=1002&cid=17

 

 

汉诺塔(又称河内塔)问题其实是印度的一个古老的传说。

开天辟地的神勃拉玛(和中国的盘古差不多的神吧)在一个庙里留下了三根金刚石的棒,第一根上面套着64个圆的金片,最大的一个在底下,其余一个比一 个小,依次叠上去,庙里的众僧不倦地把它们一个个地从这根棒搬到另一根棒上,规定可利用中间的一根棒作为帮助,但每次只能搬一个,而且大的不能放在小的上 面。计算结果非常恐怖(移动圆片的次数)18446744073709551615,众僧们即便是耗尽毕生精力也不可能完成金片的移动了。

2. 基本解题思路

2.1 首先利用第二个柱子将n -1个盘子从a移动到c

2.2 将最大的盘子从a移动到c

2.3 利用a将n - 1个盘子从b移动到c

3. 递归版本的简单实现


 //-----------------------------
// solve the Hanoi Tower problem
//-----------------------------
#include <stdio.h>
#include <stdlib.h>

void  Move(int n, char from, char to)
{
    printf("move %d from %c to %c/n",
           n,
           from,
           to);
}

// n : the number of the plates
// from : the symbol of the tower a
// tmp : like a
// to : like a
void SolveHanoiTower(int n, char from,
    char tmp, char to)
{
    // only one plate
    if(n == 1)
    {
        Move(n, from, to);
    }
    // more than one plates
    else
    {
        SolveHanoiTower(n - 1, from, to, tmp);
        Move(n, from, to);
        SolveHanoiTower(n - 1, tmp, from, to);
    }
}

 

int main()
{
    int n;

    scanf("%d", &n);
    SolveHanoiTower(n, 'a',  'b', 'c');

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值