0

I'm trying to make program knight tour using DFS but I can't solve this program.. because I alway have a message error like this

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(ArrayList.java:371) at java.util.ArrayList.get(ArrayList.java:384) at KnightTour.processKnightTour(KnightTour.java:82)

I hope someone can help me..

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]);
    }

}
false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

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

In this snippet, almost at the end of your code, you are:

  • firstly removing an element without knowing, if there is even one in the list.
  • secondly you try to get(worklist.size()-1) from a list, which can (and will be) of size 0.

There is something not quite correct in your while loop. I did not see the intentions clearly, but you should somehow make sure that workList is used correctly.

Slomo
  • 1,224
  • 8
  • 11