c++recursiontowers-of-hanoi

Understanding c++ Code: Tower of Hanoi using Recursion


i am learning about recursion in c++ but have been stumped by the following c++ code used to solve the Tower Of Hanoi problem.

void Hanoi(int m, string start, string middle, string end){
    cout << "m is equal to: " << m << endl;
    if(m == 1){
        cout << "Move Disc " << " from " << start << "  to " << end << endl;
    }
    else{
        Hanoi(m-1,start,end,middle);
        cout << "Move disc " << m << " from " << start << " to " << end << endl;
        Hanoi(m-1,middle,start,end);
    }
}
int main(){
    int discs = 3;
    Hanoi(discs, "start","middle","end");

} 

the output of the code is as follows:

m is equal to: 3
m is equal to: 2
m is equal to: 1
Move Disc  from start  to end
Move disc 2 from start to middle
m is equal to: 1
Move Disc  from end  to middle
Move disc 3 from start to end
m is equal to: 2
m is equal to: 1
Move Disc  from middle  to start
Move disc 2 from middle to end
m is equal to: 1
Move Disc  from start  to end

My general problem is i don't understand how the recursion is working. why doe m go to 1 before it executes the "if" statement? how does m go back to 2?


Solution

  • If you print it as a tree you get somthing like this:

    main
      |--> hanoi(3, ...)
      |      |
      |      |--> hanoi(2, ...)
      |      |     |
      |      |     |--> hanoi(1, ...)
      |      |     |--> hanoi(1, ...)
      |      |<----|
      |      |--> hanoi(2, ...)
      |      |     |
      |      |     |--> hanoi(1, ...)
      |      |     |--> hanoi(1, ...)
      |      |<----|
      |<-----|
      |
    

    For each call to hanoi(m, ...) it will keep call hanoi(m - 1, ...) twice unless m == 1. In the first call it will call again call hanoi(m - 1, ...) ... until m is 1.

    So going backwards when m is 2 it will call hanoi(1, ...) twice in a row:

       hanoi(2, ...)
          hanoi(1, ...)
          hanoi(1, ...)
    

    When m is 3 it will call hanoi(2, ...) twice in a row, hence:

    hanoi(3, ...)
       hanoi(2, ...)
          hanoi(1, ...)
          hanoi(1, ...)
       hanoi(2, ...)
          hanoi(1, ...)
          hanoi(1, ...)