#include <stdio.h>
int total;
void move(int n, char a, char b) {
++total;
printf("%2d-(%2d):%c==>%c\n", total, n, a, b);
}
void hanoi(int n, char a, char b, char c) {
if (n == 1) {
move(n, a, b);// 1个圆盘,直接移动
} else {
hanoi(n - 1, a, c, b);// 将上面的n-1个圆盘移到c上
move(n, a, b);// 将第n个圆盘移动到b上
hanoi(n - 1, c, b, a);// 将上面的n-1个圆盘移动到b上
}
}
int main(void) {
int n;
printf(“Please enter the number of discs:”);
scanf("%d", &n);
total = 0;
hanoi(n, ‘a’, ‘b’, ‘c’);// a移到b
printf("\tTotal:%d\n", total);
return 0;
}
汉诺塔问题c语言代码
最新推荐文章于 2023-01-24 13:42:20 发布