Tower of Hanoi(汉诺塔)

汉诺塔游戏:A,B,C三根柱子,A柱子上有由上至下依由小至大排列的n张碟子,现在要将这n张碟子移动到C柱子上,移动过程中必须保持由上至下依由小至大排列顺序。
n张碟子,需要移动步数step=2^n-1

  • c语言算法
[root@VM_0_3_centos ~]# cat alg01.c
#include <stdio.h>
int     step;

void hanoi_move(int n,char origin,char auxiliary,char destination){
        if(n==1){
                printf("Step %d:",step++);
                printf("Move sheet%d from %c to %c\n",n,origin,destination);
        }
        else{
                hanoi_move(n-1,origin,destination,auxiliary);
                printf("Step %d:",step++);
                printf("Move sheet%d from %c to %c\n",n,origin,destination);
                hanoi_move(n-1,auxiliary,origin,destination);
        }
}
int main(){
        int n;
        step=1;
        printf("input sheets number:");
        scanf("%d",&n);
        hanoi_move(n,'A','B','C');
        return 0;
}

[root@VM_0_3_centos ~]# gcc -o alg01 alg01.c
[root@VM_0_3_centos ~]# ./alg01
input sheets number:4
Step 1:Move sheet1 from A to B
Step 2:Move sheet2 from A to C
Step 3:Move sheet1 from B to C
Step 4:Move sheet3 from A to B
Step 5:Move sheet1 from C to A
Step 6:Move sheet2 from C to B
Step 7:Move sheet1 from A to B
Step 8:Move sheet4 from A to C
Step 9:Move sheet1 from B to C
Step 10:Move sheet2 from B to A
Step 11:Move sheet1 from C to A
Step 12:Move sheet3 from B to C
Step 13:Move sheet1 from A to B
Step 14:Move sheet2 from A to C
Step 15:Move sheet1 from B to C
[root@VM_0_3_centos ~]#

  • Python语言
[root@VM_0_3_centos ~]# cat alg01.py
#!/usr/bin/python
def hanoi_move(number,origin,auxiliary,destination):
        if number==1:
                print "Move sheet%d from %s to %s" %(number,origin,destination);
        else:
                hanoi_move(number-1,origin,destination,auxiliary);
                print "Move sheet%d from %s to %s" %(number,origin,destination);
                hanoi_move(number-1,auxiliary,origin,destination);

        return;


print "input the sheets number:"
number=input()
hanoi_move(number,"A","B","C");
[root@VM_0_3_centos ~]# python ./alg01.py
input the sheets number:
3
Move sheet1 from A to C
Move sheet2 from A to B
Move sheet1 from C to B
Move sheet3 from A to C
Move sheet1 from B to A
Move sheet2 from B to C
Move sheet1 from A to C
[root@VM_0_3_centos ~]#

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 专业考题类型管理运行工作负责人一般作业考题内容选项A选项B选项C选项D选项E选项F正确答案 变电单选GYSZ本规程...
    小白兔去钓鱼阅读 11,062评论 0赞 13
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 4,193评论 0赞 2
  • 选择题部分 1.()部门负责日常监督检查工作,安全巡视的同时进行消防检查,推动消防安全制度的贯彻落实。 A: 消防...
    skystarwuwei阅读 16,033评论 0赞 3
  • 问题描述在世界中心贝拿勒斯(在印度北部)的圣庙里,一块黄铜板上插着三根宝石针。印度教的主神梵天在创造世界的时候,在...
    Java红茶阅读 714评论 1赞 2
  • 未完结存粮。 -------------------------------- 襄阳的侵晨浸了薄薄的冷意,天际一抹...
    北窗鸢蓝阅读 2,996评论 0赞 3

友情链接更多精彩内容