hanoi塔问题—函数的递归调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/milustarting/article/details/71155673

实例

#include <stdio.h>
void main()
{
        void hanoi(int n,char one,char two,char three);/*对函数声明*/
        int m;
        printf("inout the number of diskes :");
        scanf("%d",&m);
        printf("The step to moveing %d diakes :\n",m);
        hanoi(m,'A','B','C');
}
void hanoi(int n,char one,char two,char three)          /*定义函数将n个碟子从one借助two移到three*/
{
        void move(char x,char y);                                        /*对函数的声明*/
        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);
}

说明

重点在于理解从注释开始的那部分函数。

hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);

此处需要不停调用函数,直到满足条件,所以起到递归作用。

猜你喜欢

转载自blog.csdn.net/milustarting/article/details/71155673