Upv*_*ote 3 java recursion exception
我想计算递归步数,并在达到某个限制时停止递归.
实际上我正在处理河内塔问题,我想限制为解决问题而执行的幻灯片数量.这是我的解决方案:
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, height - 1, buffer, source, destination);
}
}else{
throw new Exception("stop here");
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是实例: http ://ideone.com/xeN4x
我的问题是我得到了
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
Run Code Online (Sandbox Code Playgroud)
作为输出.但是应该执行5次而不是6次幻灯片.有任何想法吗?
问题是你正在测试计数器是否大于或等于1,然后将其递减2.
counter--;
// ...
counter--;
Run Code Online (Sandbox Code Playgroud)
这里的柜台可能会消极.你需要检查一下.