System.out.println 导致 stackoverflow 错误

问题描述

我正在编写一个程序来解决代码厨师提供的 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() 调用)不应进入堆栈。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)