Help with recursive puzzle solving
Updated the code to look cleaner, same problem still. Get some sort of error when I run it, but I can't see what it reads because the recursion happens too fast. The tabbing got mess up anyways :(.
I know methods have been posted and I've looked at them, but I still can't figure out what my problem is. It fails pretty soon in.
import java.util.LinkedList;
publicclass MazeSolver{
static String[][] maze;
static String wall;
staticint endX;
staticint endY;
static LinkedList pointList;
publicstaticvoid main(String[] args){
String[][] tempmaze ={
{"#","#","#","#","#","#","#","#","#","#","#","#"},
{"#","S","#"," ","#"," "," "," ","#"," "," ","E"},
{"#"," ","#"," ","#"," ","#","#","#"," ","#","#"},
{"#"," "," "," ","#"," "," "," ","#"," "," ","#"},
{"#"," ","#","#","#","#","#"," "," "," ","#","#"},
{"#"," "," "," "," "," ","#"," ","#"," "," ","#"},
{"#"," ","#","#","#"," ","#"," ","#","#"," ","#"},
{"#"," ","#"," "," "," ","#"," ","#"," "," ","#"},
{"#"," ","#"," ","#","#","#"," ","#","#","#","#"},
{"#","#","#"," ","#"," "," "," "," ","#"," ","#"},
{"#"," "," "," "," "," ","#"," "," "," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#","#","#"},
};
//i made the temp maze so i could easily create the maze matrix
maze = tempmaze;
wall ="#";
endX = 11;
endY = 1;
pointList =new LinkedList();
//prints out the maze just for a visual
for(int x=0;x<maze.length;x++){
for(int y=0;y<maze[0].length;y++){
System.out.print(maze[x][y]);
}
System.out.println();
}
System.out.println();
//prints out whether it solves the maze or not.
System.out.println(solve(1,1,-1,-1));
}
publicstaticboolean solve(int curX,int curY,int prevX,int prevY){
// |-check if previous point-| |--check if its within bounds of the maze||--check if its a wall--|
if((curX==prevX && curY==prevY) || curX>maze.length-1 || curX<0 || curY>maze[0].length-1 || curY<0 || maze[curX][curY].equals(wall)){
returnfalse;
}
//catch the point that is the end and return true for the recursing if statement
elseif(curX==endX && curY==endY){
returntrue;
}
//keep brute forcing the maze until it reaches the end point
elseif(solve(curX,curY-1,curX,curY) || solve(curX+1,curY,curX,curY) || solve(curX,curY+1,curX,curY) || solve(curX-1,curY,curX,curY)){
int[] point ={curX, curY};
//keep adding the point to the front when the maze is solved because of LIFO stack
pointList.addFirst(point);
returntrue;
}
//if somehow the maze does not have an end point, or it is somehow unreachable, return false
else
returnfalse;
}
}
Message was edited by:
ending6o6
Message was edited by:
ending6o6
Message was edited by:
ending6o6

