原题如下:
#include <stdio.h>
int j = 5;
void move(char a,char b,char c,int n)
{
if (n == 1)
{
printf("%c-->%c ", a, c);
j++;
if (j % 5 == 0)
{
printf("\n");
}
}
else
{
move(a, c, b, n - 1);
printf("%c-->%c ", a, c);
j++;
if (j % 5 == 0)
{
printf("\n");
}
move(b, a, c, n - 1);
}
}
int main()
{
int n;
while (scanf("%d", &n) && n != 0)
{
move('A', 'B', 'C', n);
printf("\n");
j = 5;
}
system("pause");
return 0;
}
分析:
void move(char a,char b,char c,int n)
{
if (n == 1)
{
printf("%c-->%c ", a, c);
j++;
if (j % 5 == 0)
{
printf("\n");
}
}
else
{
move(a, c, b, n - 1); //将上面的n-1个通过C从A移动到B
printf("%c-->%c ", a, c); //将A剩下的最大的移动到C
j++;
if (j % 5 == 0)
{
printf("\n");
}
move(b, a, c, n - 1); //再将B中剩下的n-1个移动到C即完成
}
}
此函数中,首先写出递归终止条件,即n == 1时,将最后一个也就是最大的一块从A通过B移到C。
其余的看注释就OK。
j时用于控制题目中的5个换行。
然后题目中还有一个恶心的地方就是两个步骤之间又三个空格,不然就会 presentation error~