C ++ - 不了解递归函数的流程

时间:2014-09-04 18:28:35

标签: c++ recursion data-structures towers-of-hanoi

我是一名刚刚学习数据结构的计算机工程专业的学生。今天的讲座将递归函数作为解决因子问题或排序问题的简单方法。我的教授使用了河内塔的例子,我真的想确保理解递归函数被调用的顺序。我已经尝试逐步写出函数如何执行,但我没有得到正确的序列。

我将在下面发布我的源代码,这非常简单。如果有人能帮我解释一下,我会非常感激。谢谢!

void hanoi(int N, char S, char D, char I){
    //Step1: Anchor Value or Base Case
    if(N==1){
        cout <<"Move " << N << " from " << S << " to " << D << endl;
    }
    else {
        //Step2: Make progress towards base case
        hanoi(N-1, S, I, D);
        cout << "Move " << N << " from " << S << " to " << D << endl;
        hanoi (N-1, I, D, S);
    }
}

int main(){
    int N; //Number of disks
    cout << "Enter number of discs: " << endl;
    cin >> N;
    char S = 'S'; //Source
    char D = 'D'; //Destination
    char I = 'I'; //Intermediary

    hanoi(N, S, D, I);

    system("pause");
}

1 个答案:

答案 0 :(得分:2)

使用3个磁盘执行的示例:

hanoi( 3, 'S', 'D', 'I')
    (else) 
    hanoi(2, 'S', 'I', 'D')
        (else) 
        hanoi(1, 'S', 'D', 'I')
            (cout) move 1 from 'S' to 'D'
        (cout) move 2 from 'S' to 'I'
        hanoi(1, 'D', 'I', 'S'
            (cout) move 1 from 'D' to 'I'
    (cout) move 3 from 'S' to 'D'
    hanoi(2, 'I', 'D', 'S')
        (else)
        hanoi(1, 'I', 'S', 'D')
            (cout) move 1 from 'I' to 'S'
        (cout) move 2 from 'I' to 'D'
        hanoi(1, 'S', 'D', 'I')
            (cout) move 1 from 'S' to 'D'

要理解标题,请考虑左边是“S”,“D”是中间,“I”是左边。 1是较小的磁盘,2是中型磁盘,3是较大的磁盘。