recursiontowers-of-hanoi

Recursion function to count no. of steps in tower of hanoi


Write a recursive function which returns number of steps required to solve the tower of Hanoi problem for N discs.

Input n=3 Output 7

Here is the code-

private static int counttoh(int n,String T1,String T2,String T3)
 {int count=0;

     if(n==0)
     return 1; 


     count+=counttoh(n-1,T1,T3,T2);
     count+=counttoh(n-1,T3,T2,T1);

     return count;
 }

My function counttoh is giving 4 as the output, if I am doing return count-1 it is giving 1 , can anyone help me with the problem.


Solution

  • For solving tower of Hanoi, need to move all rings on top of the bottom one (n - 1), then move the bottom one (+ 1), then move all the others back on top (n - 1 again).

    public static int countMoves(int n) {
    
        if (n == 0) return 0;
    
        // count(n-1) + 1 + count(n-1)
        return 2 * countMoves(n - 1) + 1;
    }