好吧所以我一直在尝试使用这种寻路算法来搜索迷宫,而且我遇到了一个似乎近乎琐碎的问题,但我还没有找到一个优雅的解决方案。
该方法应该检查哪个空格在以后的方法中有效。
因此,错误发生在边缘位置,因为它检查双字符数组之外的空格。是否需要提前检查以确定其是否为空?或者我是否需要添加一堆ifs来检查它是否为行[0]或列[0](或两者!)并相应调整?
说这是迷宫:( 0 =空,可穿越的空间,1 =墙)
01010
01000
00010
01110
public static boolean[] isValidPath(char [][] maze, Position current){
int currentRow = current.i;
int currentColumn = current.j;
boolean[] intersection= new boolean[4];
//[right, down, up, left]
//In order of priority to get to bottom right
//right
intersection[0] = (maze[currentRow][currentColumn+1] == '0');
//down
intersection[1] = (maze[currentRow+1][currentColumn] == '0');
//up
intersection[2] = (maze[currentRow-1][currentColumn] == '0');
//left
intersection[3] = (maze[currentRow][currentColumn-1] == '0');
return intersection;
}
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
0 1 0 1 0
at PathFinder.isValidPath(PathFinder.java:73)
0 0 0 1 0
at PathFinder.stackSearch(PathFinder.java:154)
0 1 0 0 0
at PathFinder.main(PathFinder.java:47)
0 1 0 1 1
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
0 1 0 0 0
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
答案 0 :(得分:0)
优雅的解决方案:将迷宫插入一个较大的迷宫(每边+1个),所有边缘都作为墙壁,只检查原始的迷宫位置
e.g。
1111111个
1010101个
1010001个
1000101个
1011101个
1111111