学习算法的时候第一个递归程序就是汉诺塔,第一次只是理解个全局思想,每一步递归的细节不是很明白,总是感觉不大对劲。今天又看见汉诺塔问题了,一步步分析了一下。下面是手工图。
#include <stdio.h>
#include <stdlib.h>
void hanoi(int ,char ,char ,char );
int main()
{
int m;
printf("input the number of diskes:");
scanf("%d",&m);
printf("The step to move %d diskes:\n",m);
hanoi(m,'A','B','C');
system("pause");
}
void hanoi(int n,char a,char b,char c)
{
static int i=1;
if(n==1)
printf("(%d) %c to %c\n",i++,a,b);
else
{
hanoi(n-1,a,c,b);
printf("(%d) %c to %c\n",i++,a,b);
hanoi(n-1,c,b,a);
}
}