【问题标题】:Checking Valid Next Position for Maze ArrayIndexOutOfBounds检查 Maze ArrayIndexOutOfBounds 的有效下一个位置
【发布时间】:2015-07-23 01:02:33
【问题描述】:

好的,所以我一直在尝试使这种寻路算法在迷宫中搜索,我遇到了一个看似微不足道的问题,但我还没有找到一个优雅的解决方案。

这个方法应该检查哪些空格是有效的,以便在以后的方法中进行测试。

所以错误发生在边缘位置,因为它检查了双字符数组之外的空格。是否需要提前检查以确定其是否为空?还是我需要添加一堆 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)

【问题讨论】:

  • 使用堆栈跟踪发布整个异常。
  • 请将此信息(使用edit)添加到您的问题中。
  • 创建一个getTile(row, column),返回坐标处的项目,如果在外面,则返回1。然后你可以调用它而不是在每个数组引用上添加检查
  • 并非每个位置都有 4 个相邻的位置。你需要控制你的边界。
  • 是的,我知道我需要控制边界,它只是如何做到这一点。有没有像 compareTo() 方法这样不会抛出错误并且默认为 false 的“安全方式”?

标签: java arrays indexoutofboundsexception path-finding


【解决方案1】:

优雅的解决方案:将迷宫插入一个较大的迷宫(每侧+1),所有边缘都作为墙壁,只检查原始迷宫位置

例如
1111111
1010101
1010001
1000101
1011101
1111111

【讨论】:

  • 由于其他已经运行的方法,这将导致另一组问题
  • 如果是这样,您可以在 isValidPath 中进行整个插入,并在完成后将其废弃。
猜你喜欢
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
相关资源
最近更新 更多