汉诺塔问题

    技术2022-05-19  25

    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 avoid 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)