c语言 递归算法解决汉诺塔问题

//汉诺塔问题是一个典型的使用递归算法解决的问题
#include <stdio.h>

int main()
{
    void hanoi(int n,char one,char two,char three);
    int m;
    printf("the number of disks:");
    scanf("%d",&m);
    printf("move %d diskes:\n",m);
    hanoi(m,'A','B','C');
}
void hanoi(int n,char one,char two,char three)
{
   void move (char x,char y);
   if(n==1)//临界条件
       move(one,three);
   else//递归公式
   {
      hanoi(n-1,one,three,two);//如果想把最大的一个圆盘由A——>C,首先要把它上面的n-1个圆盘由A->B
      move(one,three);
      hanoi(n-1,two,one,three);//最后再把n-1个圆盘由B->C
   }
}
void move(char x,char y)
{
    printf("%c-->%c\n",x,y);
}

猜你喜欢

转载自blog.csdn.net/ling_cmd/article/details/78296421