java - 寻路 - StackOverflowError

标签 java recursion stack-overflow path-finding

我在寻路方面遇到问题:

起点为 0,0,终点为右下角的“C”。它在

处抛出一个异常java.lang.StackOverflowError
if(getPath(x, y+1)==true){ 
        return true;
    }

if(getPath(x, y-1)==true){ 
        return true;
    }

方法如下

public static boolean getPath(int x,int y, int num){


    if(x==startX-1|| y==startY-1 || x==endX+1 || y==endY+1){
        return false;
    }

    if (" C".equals(array[x][y])){
        return true;
    }

    if ("# ".equals(array[x][y])||"x".equals(array[x][y])){
        return false;
    }

    if ("[]".equals(array[x][y])){
        array[x][y]="+";
    }

    if(getPath(x, y+1,num)==true){ //vpravo
        return true;
    }

    if(getPath(x+1, y,num)==true){ //dolu
        return true;
    }
    if(getPath(x-1, y,num)==true){ //nahoru
        return true;
    }
    if(getPath(x, y-1,num)==true){ //vlevo
        return true;
    }

    if("+".equals(array[x][y])){
        array [x][y]="x";
    }

    return false; 

}


}

我使用的值(value)观

public static Random r = new Random();
public static int i1 = r.nextInt(4) + 4;

public static int startX=0;
public static int startY=0;

public static int endX=i1-1;
public static int endY=i1-1;
public static int rows = i1;
public static int columns = i1;
public static String[][] array = new String[rows][columns];

我有 i3-i14 用于随机障碍,它们是这样定义的

public static int i3 = r.nextInt(4) ;
...
public static int i14 = r.nextInt(4) ;

在我更改比较后,它仍然抛出异常

编辑:我想我已经找到问题了。当 IF 比较“+”并将其替换为“x”时

if("+".equals(array[x][y])){
        array [x][y]="x";

你能帮我解决这个问题吗?谢谢

最佳答案

首先,您需要使用 .equals(.) 进行字符串比较,而不是 ==

试试这个老栗子:

How do I compare strings in Java?

之后,避免重新跟踪步骤的逻辑可能会开始起作用,并且您可以避免失控的递归。

关于java - 寻路 - StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30345613/

相关文章:

java - 关于 ESAPI 日志事件

Java:泛型类型

sql - 查询层次结构中父级之下有多少级别

memory-management - 嵌入式系统的内存错误检测器?

java - 不同类型的单例模式

java - 如何将 INTEGER/NULL 绑定(bind)到 ? Android 中带有 rawQuery SelectionArgs 的占位符?

r - R : options(expressions=) to non-computer scientists 的解释

sql-server - 用于递归和排序的 SQL Server CTE

java - 在没有 StackOverflowError 的情况下序列化 Java 对象

c - 我怎样才能在程序的垂死挣扎中分配更多的堆栈?