我正在编写一个程序来解决代码厨师提供的 RUSH HOUR 问题
我正在使用 DFS 来解决问题。在 DFS 的递归函数中,我基于 DEBUG 变量打印消息。
首先设置DEBUG变量false
有一个汽车类
class Car {
boolean isVertical;
char c;
int x;
int y;
int length;
public Car(boolean val, char ch, int i, int j, int l) {
c = ch;
isVertical = val;
x = i;
y = j;
length = l;
}
}
// DFS 递归函数
private int findPath(int carId, int index) {
if (isPathCleared()) {
answerFound = true;
return index;
}
Car car = carArray[carId];
if (DEBUG)
System.out.println("car id: " + (char)(index+'A'));
// some lines of code
call to findPath()
}
或
private int findPath(int carId, int index) {
if (isPathCleared()) {
answerFound = true;
return index;
}
Car car = carArray[carId];
if (DEBUG)
System.out.println("car id: " + car.c);
// some lines of code
call to findPath()
}
以上递归函数抛出java.lang.StackOverflowError
但下面的递归函数工作正常
private int findPath(int carId, int index) {
if (isPathCleared()) {
answerFound = true;
return index;
}
Car car = carArray[carId];
if (DEBUG)
System.out.println("just string message");
// some lines of code
call to findPath()
}
或
private int findPath(int carId, int index) {
if (isPathCleared()) {
answerFound = true;
return index;
}
Car car = carArray[carId];
if (DEBUG)
System.out.println("car id: " + (index+100));
// some lines of code
call to findPath()
}
有人可以解释这种行为吗?由于它是在 false 条件下写入的,因此它(System.out.println() 调用)不应进入堆栈。