汉诺塔问题

自闭症网瘾萝莉.ら 提交于 2019-12-15 05:42:03

汉诺塔(Hanoi)是必须用递归方法才能解决的经典问题。(这话不是我说的,是题目自带的)把圆盘从下面开始按大小顺序重新摆放到第二根柱子上,并且规定,每次只能移动一个圆盘,在小圆盘上不能放大圆盘。

**输入格式要求:"%d" 提示信息:“Input the number of disks:”
**输出格式要求:“Steps of moving %d disks from A to B by means of C:\n” “Move %d: from %c to %c\n”

程序运行示例如下:
Input the number of disks:3
Steps of moving 3 disks from A to B by means of C:
Move 1: from A to B
Move 2: from A to C
Move 1: from B to C
Move 3: from A to B
Move 1: from C to A
Move 2: from C to B
Move 1: from A to B

#include <stdio.h>
void Hanoi(int n, char a, char b, char c);
void Move(int n, char a, char b);
int main()
{                    
    int n;
    printf("Input the number of disks:");
    scanf("%d", &n);
    printf("Steps of moving %d disks from A to B by means of C:\n", n);
    Hanoi(n, 'A', 'B', 'C'); /*调用递归函数Hanoi()将n个圆盘借助于C由A移动到B*/
    return 0;
}                    
/* 函数功能:用递归方法将n个圆盘借助于柱子c从源柱子a移动到目标柱子b上 */
void Hanoi(int n, char a, char b, char c)
{                    
    if (n == 1)
    {                    
        Move(n, a, b);       /* 将第n个圆盘由a移到b */
    }
    else
    {                    
        Hanoi(n - 1, a, c, b); /* 递归调用Hanoi(),将第n-1个圆盘借助于b由a移动到c*/
        Move(n, a, b);       /* 第n个圆盘由a移到b */
        Hanoi(n - 1, c, b, a); /*递归调用Hanoi(),将第n-1个圆盘借助于a由c移动到b*/
    }
}                    
/* 函数功能:  将第n个圆盘从源柱子a移到目标柱子b上 */
void Move(int n, char a, char b)
{                    
    printf("Move %d: from %c to %c\n", n, a, b);
}               
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!