1. 程式人生 > >hanoi塔問題—函式的遞迴呼叫

hanoi塔問題—函式的遞迴呼叫

例項

#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);

此處需要不停呼叫函式,直到滿足條件,所以起到遞迴作用。