我想计算递归步数,并在达到某个限制时停止递归。
其实我正在处理河内塔问题,我想限制为解决问题而执行的幻灯片数量。这是我的解决方案:
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");
}
}
}
以下是实例: 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
作为输出。但是应该执行5次而不是6次幻灯片。有什么想法吗?
答案 0 :(得分:5)
问题是你正在测试计数器是否大于或等于一个,然后将其递减两个。
counter--;
// ...
counter--;
这里的计数器可能会消极。你需要检查一下。
答案 1 :(得分:1)
这是一个递归调用counter
次
public void callMe(int counter){
if(counter == 1 ){
return;
}else{
callMe(--counter);
}
}
代码中的有counter--;
两次,因此在许多情况下不符合条件
答案 2 :(得分:1)
由于您要计算移动次数并且不递归深度,因此您需要存储在每个步骤中进行的移动次数。像这样:
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, hoehe - 1, ablage, quelle, ziel);
}
return counter;
}
然后,您获得预期结果:
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
答案 3 :(得分:0)
你必须在每次这样的减量测试你的计数器:
public static void 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);
}else{
if (--counter == 0) throw new Exception("hier stoppen");
slide(counter, hoehe - 1, quelle, ziel, ablage);
System.out.println("move "+ hoehe +" from " +
quelle + " to " + ziel);
if (--counter == 0) throw new Exception("hier stoppen");
slide(counter, hoehe - 1, ablage, quelle, ziel);
}
}