汉诺塔

作者: gtxe | 来源:发表于2018-10-28 16:21 被阅读0次

汉诺塔是一个发源于印度的益智游戏,也叫河内塔。相传它源于印度神话中的大梵天创造的三个金刚柱,一根柱子上叠着上下从小到大64个黄金圆盘。大梵天命令婆罗门将这些圆盘按从小到大的顺序移动到另一根柱子上,其中大圆盘不能放在小圆盘上面。当这64个圆盘移动完的时候,世界就将毁灭。


image.png

汉诺塔问题源于印度神话 (难题,认真领悟,反复领悟)

求解思路和步骤:
将n个盘从A移动到C可以分解为3个步骤:
1.将A上n-1个盘借助C座先移动到B座上;
2.把A座上剩下的一个盘移到C座上;
3.将n-1个盘从B座借助于A移动到C座上。
用move函数实现上面第2类操作,将一个盘从one移动到three。
用Hanoi函数实现将n个盘子从one 移动到three座的过程(借助two)。

#include <stdio.h>
#include <math.h>
#include <string.h>
long sum=0;

int main()
{
    void hanoi(int n,char one,char two,char three);
    int m;
    printf("input the number of disks:");
    scanf("%d",&m);
    printf("the step to move %d disks:\n",m);
    hanoi(m,'A','B','C');
    printf("the total step are %d",sum);
    return 0;
}

void hanoi(int n,char one,char two,char three)
{
    void move(char x,char y);
    if(n==1)
        move(one,three);
    else
    {
        hanoi(n-1,one,three,two);
        move(one,three);
        hanoi(n-1,two,one,three);
    }
}

void move(char x,char y)
{
    sum++;
    printf("%c->%c\n",x,y);
}

image.png

相关文章

网友评论

      本文标题:汉诺塔

      本文链接:https://www.haomeiwen.com/subject/baydtqtx.html