汉诺塔(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);
}
来源:CSDN
作者:绀香零八
链接:https://blog.csdn.net/qq_45475271/article/details/103482116