以递归方式求解汉诺塔的问题(n, a, b, c),即将N个盘子从起始柱(标记为“a”)通过借助柱(标记为“b”)移动到目标柱(标记为“c”),并保证每个移动符合汉诺塔问题的要求。
输入格式:
输入为一个正整数N,即起始柱上的盘数。
输出格式:
每个操作(移动)占一行,按柱1 -> 柱2
的格式输出。
输入样例:
3
输出样例:
a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c
#include<stdio.h>
#include<stdlib.h>
void hanoi(int n,char one,char two,char three)
{
void move(char x,char y);//对move函数的声明
if(n==1) move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void move(char x,char y)
{
printf("%c -> %c\n",x,y);
}
int main()
{
void hanoi(int n,char one,char two,char three);
//对hanoi函数的声明
int m;
// printf("input the number of diskes:");
while(scanf("%d",&m)!=EOF)
{
// printf("The step to moveing %d diskes:\n",m);
hanoi(m,'a','b','c');
}
system("pause");
}