Search code examples
javadata-structurestowers-of-hanoi

Problem in understanding flow of recursion in towers of hanoi


I am recently learning data structures and algorithm.I got simply working code of towers of hanoi.

package linkedlist;

public class TowrerOfHanoi {

    public static void main(String[] args) {
        TowrerOfHanoi toh=new TowrerOfHanoi();
        toh.move(3,'A','C', 'B');
    }

    public void move(int numberOfDisc,char from,char to,char inter) {
        System.out.println(numberOfDisc);
        if(numberOfDisc==1) {
            System.out.println("Moving disc 1 from"+from
                    +"to"+to);
        }
        else {
            move(numberOfDisc-1,from,inter,to);
            System.out.println("Moving disc "+numberOfDisc+"from"+from
                    +"to"+to);  //confusion at this point
            move(numberOfDisc-1,inter,to,from);
        }

    }

}

No of disc=3 The move function is called and

At first step: move(3,A,C,B) is passed and it goes to else block.
2nd step:Recursion is seen and  move(2,A,B,C) is called.
3rd step:Recursion is seen and  move(1,A,B,C) is called.

Since noofdisc=1 so,it goes to first if block and I got this:

3
2
1
Moving disc 1 fromAtoC

I am clear upto this point and after this i while debugging i see noofdisk=2 in console:

enter image description here

Since ,our last recursion called was move(1,A,B,C) how is the noofdisk=2? I am getting stuck at this point.Please help me to how I am getting noofdisk=2 at this step? The code is working fine for towers of hanoi problem.


Solution

  • When I am thinking about recursion problems, I picture every new recursive call as a first in first out stack, where most recent call is handled first. When move is called with noof==2, it subtracted noof to 1 for only that call and therefore hit your base case and printed "Moving disc 1 fromAtoC" and finished the call. In the previous call, noof still equals 2 because it never assigned noof in the local instance only simply passed it decremented.