Computing recursive steps in Java

I want to count the number of recursive steps and stop recursion when a certain limit is reached

Actually, I'm dealing with the Hanoi Tower problem. I want to limit the number of slides to solve the problem This is my solution:

class HanoiNK{

    public static void main(String args[]){

            int n = 4;
            int k = 5;

            try{
                slide(k,n,'A','B','C');
            }catch(Exception e){
                System.out.println(e);
            }
    }

    public static void slide(int counter,int height,char source,char buffer,char destination) throws Exception{      
        if(counter > 0){
            if(height == 1){                                
                System.out.println("move "+ height +" from " +
                                                source + " to " + destination);
            }else{  
                counter--;
                slide(counter,height - 1,source,destination,buffer);    
                System.out.println("move "+ hoehe +" from " +
                                                source + " to " + destination);
                counter--;
                slide(counter,buffer,destination);    
            }
        }else{
            throw new Exception("stop here");
        }
    }
}

This is a field example: http://ideone.com/xeN4x

My problem is that I got it

move 1 from A to B
move 2 from A to C
move 1 from B to C
move 3 from A to B
move 1 from C to A
move 2 from C to B
java.lang.Exception: stop

As output However, you should perform 5 slides instead of 6 slides Any ideas?

Solution

Since you want to calculate the number of moves rather than the recursive depth, you need to store the number of moves made in each step Something like this:

public static int slide(int counter,int hoehe,char quelle,char ablage,char ziel)
throws Exception{         
    if (hoehe == 1) {          
        System.out.println("move "+ hoehe +" from " +                                             
                quelle + " to " + ziel);   
        if (--counter == 0) throw new Exception("hier stoppen"); 
    } else {     
        counter = slide(counter,hoehe - 1,quelle,ziel,ablage);     
        System.out.println("move "+ hoehe +" from " +          
                quelle + " to " + ziel);             
        if (--counter == 0) throw new Exception("hier stoppen"); 
        counter = slide(counter,ablage,ziel);       
    }     
    return counter;
}

Then you get the desired results:

move 1 from A to B
move 2 from A to C
move 1 from B to C
move 3 from A to B
move 1 from C to A
java.lang.Exception: hier stoppen
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>