java - 使用深度优先搜索算法的 Knight Tour

标签 java depth-first-search knights-tour

我正在尝试使用DFS制作程序骑士之旅,但我无法解决这个程序..因为我总是有这样的消息错误

线程“AWT-EventQueue-0”中的异常java.lang.ArrayIndexOutOfBoundsException:-1 在 java.util.ArrayList.elementData(ArrayList.java:371) 在 java.util.ArrayList.get(ArrayList.java:384) 在 KnightTour.processKnightTour(KnightTour.java:82)

希望有人能帮助我..

public void processKnightTour(int indexX, int indexY){
    System.out.println(indexX);
    System.out.println(indexY);
    int[] x={2,2,-2,-2,1,1,-1,-1};
    int[] y={1,-1,1,-1,2,-2,2,-2};
    int countPath=0;
    workList = new ArrayList();
    node[indexX][indexY] = 1;
    workList.add(new Coordinate(indexX, indexY));
    current =(Coordinate) workList.get(workList.size()-1);
    boolean statusChild;
    while(node[current.row][current.column] != 64){
        statusChild = false;
        for(int loop=0; loop<8; loop++){
            if(current.row+x[loop]>=0 && current.row+x[loop]<=7 && current.column+y[loop]>=0 && current.column+y[loop]<=7){
                if(node[(current.row+x[loop])][(current.column+y[loop])]==0){
                    workList.add(new Coordinate(current.row+x[loop], current.column+y[loop], current));
                    statusChild = true;
                }                    
            }
        }
        if(statusChild == true){
            workList.remove(workList.indexOf(current));
        }else{
            if(workList.size()-2 >= 0){
                after = (Coordinate) workList.get(workList.size()-2);
                if(current.nodeParent.equals(after.nodeParent)){

                }else{
                    node[current.nodeParent.row][current.nodeParent.column] = 0;
                }
            }
            node[current.row][current.column] = 0;                
            workList.remove(workList.size()-1);
        }
        current = (Coordinate) workList.get(workList.size()-1);
        node[current.row][current.column] = (node[current.getParent().row][current.getParent().column])+1;
        countPath++;
        //System.out.println(countPath+", "+workList.size()+", "+node[current.column][current.row]);
    }

}

最佳答案

        workList.remove(workList.size()-1);
    }
    current = (Coordinate) workList.get(workList.size()-1);

在此代码片段中,几乎在代码末尾,您是:

  • 首先在不知道列表中是否有元素的情况下删除一个元素。
  • 其次,您尝试从列表中获取get(worklist.size()-1),该列表的大小可以(并且将会)为 0。

您的 while 循环中有一些不太正确的内容。我没有清楚地看到意图,但您应该以某种方式确保正确使用 workList

关于java - 使用深度优先搜索算法的 Knight Tour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033939/

相关文章:

java - 当路径包含(空白和数字)而不仅仅是空白时,如何在 cmd 中运行应用程序

java - Android相机预览回调缓冲区未填充: is always full of zeros

c++ - 如何转换dfs

c++ - 遍历任意深度树进行删除的最快方法?

algorithm - 根据特定条件创建图表

c - 骑士之旅- 给定 n 步,骑士在 n 步中有多少种选择可以从 (1,1) 移动到 (8,8)?

c++ - 使用回溯的代码骑士之旅没有显示任何输出

java - MemoryUsage max随时间变化

Java - 通过 channel 传输大文件 - NIO

algorithm - 寻找封闭骑士之旅的快速算法