需要帮助搞清楚这个c ++代码如何评估

时间:2015-01-18 21:35:58

标签: c++ towers-of-hanoi

此代码如何评估?它给了我正确的解决河内问题的塔,但我不明白评估的顺序。

void moveDisks(int n, const char* pegA, const char* pegB, const char* pegC)

{
    if (n == 0)
    {
        return;
    }

    moveDisks(n-1, pegA, pegC, pegB);
    std::cout << "Move disk from " << pegA << " to " << pegC << std::endl;  
    moveDisks(n-1, pegB, pegA, pegC);
}

1 个答案:

答案 0 :(得分:1)

评论是绝对正确的,但另外这里是一个伪代码/ callstack /输出的东西,可能有助于概念化它:

moveDisks(4, "A", "B", "C");
    moveDisks(3, "A", "C", "B");
        moveDisks(2, "A", "B", "C");
            moveDisks(1, "A", "C", "B");
                Move disk from A to B
            Move disk from A to C
            moveDisks(1, "B", "A", "C");
                Move disk from B to C
        Move disk from A to B
        moveDisks(2, "C", "A", "B");
            moveDisks(1, "C", "B", "A");
                Move disk from C to A
            Move disk from C to B
            moveDisks(1, "A", "C", "B");
                Move disk from A to B
    Move disk from A to C
    moveDisks(3, "B", "A", "C");
        moveDisks(2, "B", "C", "A");
            moveDisks(1, "B", "A", "C");
                Move disk from B to C
            Move disk from B to A
            moveDisks(1, "C", "B", "A");
                Move disk from C to A
        Move disk from B to C
        moveDisks(2, "A", "B", "C");
            moveDisks(1, "A", "C", "B");
                Move disk from A to B
            Move disk from A to C
            moveDisks(1, "B", "A", "C");
                Move disk from B to C

如果您阅读有关递归或开始使用类似评论建议的调试器(您应该!),您会看到很多这样的图表。