/**
hanoi
input the number of dishes and output the methods
A->B->C
**/
#include <stdio.h>
static long count=0;
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
void hanoi(int n,char first,char second,char third)
//n为盘子的数目,first,second,third分别表示三座塔
{
if(n==1)
{
move(first,third);
count++;
}
else
{
hanoi(n-1,first,third,second);
move(first,third);
count++;
hanoi(n-1,second,first,third);
}
}
void main()
{
int n;
printf("请输入盘子的个数:");
scanf("%d",&n);
hanoi(n,'A','B','C');
printf("共移动了%d次:\n",count);
}
hanoi塔问题(经典递归)
最新推荐文章于 2024-04-22 21:34:58 发布