I have these two methods, one is called findPath, which should recursively find the path through the maze. And another one called solve, which I think should just call findPath. The problem I am facing now is that I keep getting an array out of bounds exception. I think it's at the part where I create variable up in findPath.But I wrote a method to check if the move is valid. Here is the code:
private static boolean isLegal(int row, int col){
if(row < 0 || row >= numRows){
return false;
}
if(col < 0 || col >= numCols){
return false;
}
return false;
}
public MazeLocationList solve() {
findPath(0,1,8,9);
return path;
}
private boolean findPath(int fromRow, int fromCol, int toRow, int toCol) {
boolean solved = false;
visited = new boolean [numRows][numCols];
char right = maze[fromRow][fromCol+1];
char left = maze[fromRow][fromCol-1];
char up = maze[fromRow-1][fromCol];
char down = maze[fromRow+1][fromCol];
if (right == ' ' && isLegal(fromRow,fromCol+1) && visited[fromRow][fromCol+1]==false) {
point = new MazeLocation(fromRow,fromCol+1);
path.insertTail(point);
solved= findPath(fromRow, fromCol+1, toRow, toCol);
}
if (left == ' ' && isLegal(fromRow,fromCol-1) && visited[fromRow][fromCol-1]==false) {
point = new MazeLocation(fromRow,fromCol-1);
path.insertTail(point);
solved= findPath(fromRow, fromCol-1, toRow, toCol);
}
if (up == ' ' && isLegal(fromRow+1,fromCol) && visited[fromRow+1][fromCol]==false) {
point = new MazeLocation(fromRow+1,fromCol);
path.insertTail(point);
solved= findPath(fromRow+1, fromCol, toRow, toCol);
}
if(down == ' ' && isLegal(fromRow-1,fromCol) && visited[fromRow-1][fromCol]==false) {
point = new MazeLocation(fromRow-1,fromCol);
path.insertTail(point);
solved= findPath(fromRow-1, fromCol,toRow,toCol);
}
return solved;
}
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire