|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这答案是如何实现的呢
Steps of moving 3 disks from A to C by means of B:
Move 1: A to C
Move 2: A to B
Move 1: C to B
Move 3: A to C
Move 1: B to A
Move 2: B to C
Move 1: A to C
第一次递归不是 n-1 吗 不是应该输出 Move 2:吗?
//Think Different !!!
/*
//程序功能:通过递归实现汉诺塔;
*/
#include <stdio.h>
void move(int n, char source, char goal); //n 为需要移动的圆盘的数量, source 为最开始的圆盘所在柱子的编号,
//temp 为中转的圆盘的柱子的编号, goal 为最终圆盘所在的所在柱子的编号
void moveTower(int n, char source, char temp, char goal);
int main()
{
int n;
printf("Please enter the number of disks:");
scanf("%d", &n);
printf("Steps of moving %d disks from A to C by means of B:\n", n);
moveTower(n, 'A', 'B', 'C');
return 0;
}
void move(int n, char source, char goal)
{
printf("Move %d: %c to %c\n", n, source, goal);
}
void moveTower(int n, char source, char temp, char goal)
{
if(n == 1)
move(n, source, goal);
else
{
moveTower(n - 1, source, goal, temp);
move(n, source, goal);
moveTower(n - 1, temp, source, goal);
}
}
|
-
-
|