I'm solving a maze using recursion. my matrix look like this
char maze[][] =
{
{'#','#','#','#','#','#','#','#','#','#','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#','#','#','#',' ','#','#','#','#','#','#'},
{'#',' ',' ',' ',' ','#',' ',' ',' ',' ','X'},
{'#',' ',' ',' ',' ','#',' ',' ',' ',' ','#'},
{'#',' ','#','#','#','#','#','#',' ','#','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#','#','#','#','#','#','#','#','#','#','#'},
};
this is prototype of the bigger matrix.
my solve recursion method looks like this
private void solve(int x, int y) {
// set everything to false
wasHere = new boolean[maze.length][maze[1].length];
correctPath = new boolean[maze.length][maze[1].length];
for (int i = 0; i < maze.length; i++){
// Sets boolean Arrays to default values
for (int j = 0; j < maze[i].length; j++){
wasHere[i][j] = false; // set everything to false
correctPath[i][j] = false;
}
}
boolean b = solveRecursion(1,1);
System.out.println(b);
}
as you can notice here I'm returning a boolean and it should give me a true if I find a path. But it is keep giving me false. I'm not sure about the logical errors that I'm making in my solveRecursion method. Here's the method
private boolean solveRecursion(int x, int y) {
if (x == endX && y == endY){
return true;
}
if (maze[x][y] == '#' || wasHere[x][y]){
return false;
}
wasHere[x][y]=true;
if (x != 0) // Checks if not on left edge
if (solveRecursion(x-1, y)) { // Recalls method one to the left
correctPath[x][y] = true; // Sets that path value to true;
maze[x][y]='S';
return true;
}
if (x != maze[0].length ) // Checks if not on right edge
if (solveRecursion(x+1, y)) { // Recalls method one to the right
correctPath[x][y] = true;
maze[x][y]='S';
return true;
}
if (y != 0) // Checks if not on top edge
if (solveRecursion(x, y-1)) { // Recalls method one up
correctPath[x][y] = true;
maze[x][y]='S';
return true;
}
if (y != maze.length) // Checks if not on bottom edge
if (solveRecursion(x, y+1)) { // Recalls method one down
correctPath[x][y] = true;
maze[x][y]='S';
return true;
}
return false;
}
endX =3;
endY =10;