使用深度优先搜索算法的骑士之旅

时间:2012-06-14 13:18:31

标签: java depth-first-search

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

线程“AWT-EventQueue-0”中的异常java.lang.ArrayIndexOutOfBoundsException:-1     at java.util.ArrayList.elementData(ArrayList.java:371)     at 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]);
    }

}

1 个答案:

答案 0 :(得分:1)

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

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

  • 首先删除一个元素,如果列表中只有一个,则不知道。
  • 其次,您尝试从列表中get(worklist.size()-1),该列表可以(并且将会)大小为0.

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