#include<stdio.h>
void hanoi(int N,char A,char B,char C)
{
if(N==1)/*将A座上剩下的第N个盘子移动到C座上*/
printf("move dish %d from %c to %c\n",N,A,C);/*打印移动步骤*/
else
{
hanoi(N-1,A,C,B);/*借助C座将N-1个盘子从A座移到B座*/
printf("move dish %d from %c to %c\n",N,A,C);/*打印移动步骤*/
hanoi(N-1,B,A,C);/*借助A座将N-1个盘子从B座移到C座*/
}
}
main()
{
int n;
printf("Please input the nuber of dishes;");
scanf("%d",&n);/*输入要移动的盘子个数*/
printf("The steps to move %2d dishes are:\n",n);
hanoi(n,'A','B','C');/*调用递归函数*/
}
Please input the nuber of dishes;3
The steps to move
3 dishes are:
move dish 1 from A to C
move dish 2 from A to B
move dish 1 from C to B
move dish 3 from A to C
move dish 1 from B to A
move dish 2 from B to C
move dish 1 from A to C
Press any key to continue
Please input the nuber of dishes;4
The steps to move
4 dishes are:
move dish 1 from A to B
move dish 2 from A to C
move dish 1 from B to C
move dish 3 from A to B
move dish 1 from C to A
move dish 2 from C to B
move dish 1 from A to B
move dish 4 from A to C
move dish 1 from B to C
move dish 2 from B to A
move dish 1 from C to A
move dish 3 from B to C
move dish 1 from A to B
move dish 2 from A to C
move dish 1 from B to C
Press any key to continue