递归如何到达cout语句?

时间:2018-10-05 11:38:55

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

我有这个功能来解决河内塔的问题,幸运的是,它运行良好,但是任何人都可以向我解释一下,如果在mout = 0的情况下该函数在cout语句之前调用了self,那么它将如何到达cout声明,甚至本身的另一个调用?

#include <iostream>

using namespace std;

void Hanoi(int m, char a, char b, char c){
if(m == 1){
    cout << "Move disc " << m << " from " << a << " to " << c << endl;
 }else{  
      Hanoi(m-1, a,c,b);
      cout << "Move disc " << m << " from " << a << " to " << c << endl;
      Hanoi(m-1,b,a,c);
  }
}

int main(){

int discs;
cout << "Enter the number of discs: " << endl;
cin >> discs;
Hanoi(discs, 'A', 'B', 'C');


 return 0;
}

1 个答案:

答案 0 :(得分:1)

呼叫Hanoi(m),其中m > 1:首先,它执行Hanoi(m-1)和所有产生的呼叫。然后它执行cout。然后,它执行Hanoi(m-1)并再次调用所有结果。

考虑m == 3

Hanoi(3)
    Hanoi(2)
        Hanoi(1)
            cout
        cout
        Hanoi(1)
            cout
    cout
    Hanoi(2)
        Hanoi(1)
            cout
        cout
        Hanoi(1)
            cout