I've been trying to create a maze solving algorithm in java. I've tried to do it with backtracking recursion.Here is my code:
public static boolean solver(String[][] maze, int i, int j){
display(maze);//prints maze
System.out.println();
maze[i][j] = "*";
if(maze[i][j+1] == "E" || maze[i][j-1] == "E" || maze[i+1][j] == "E" || maze[i-1][j] == "E")
display(maze);
else if(maze[i][j+1] != " " && maze[i][j-1] != " " && maze[i+1][j] != " " && maze[i-1][j] != " "){
maze[i][j] = " ";
return false;
}
if(maze[i][j+1] == " ")
if(!solver(maze,i,j+1))
maze[i][j] = " ";
if(maze[i][j-1] == " ")
if(!solver(maze,i,j-1))
maze[i][j] = " ";
if(maze[i+1][j] == " ")
if(!solver(maze,i+1,j))
maze[i][j] = " ";
if(maze[i-1][j] == " ")
if(!solver(maze,i-1,j))
maze[i][j] = " ";
return true;
}
and here is main method:
String[][] maze = {{"#","S","#","#","#","#","#","#","#","#","#","#","#"},
{"#"," "," "," "," "," ","#"," "," "," "," "," ","#"},
{"#"," ","#","#","#","#","#"," ","#","#","#"," ","#"},
{"#"," "," "," "," "," ","#"," ","#"," ","#"," ","#"},
{"#"," ","#","#","#"," ","#"," ","#"," ","#"," ","#"},
{"#"," "," "," ","#"," ","#"," "," "," ","#"," ","#"},
{"#"," "," "," ","#"," ","#"," "," "," ","#"," ","#"},
{"#"," ","#"," ","#"," "," "," "," "," "," "," ","#"},
{"#","#","#"," ","#","#","#","#","#","#","#","#","#"},
{"#"," "," "," ","#"," "," "," "," "," "," "," ","#"},
{"#"," ","#","#","#"," ","#","#","#","#","#"," ","#"},
{"#"," "," "," "," "," ","#"," "," "," "," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#","#","E","#"}};
solver(maze,1,1);
This algorithm can solve a maze but there is a bug in this code and I couldn't solve the bug.
Output:
#S###########
#*****# #
# ##### ### #
# # # # #
# ### # # # #
# # # # #
# # # # #
# # # #
### #########
# # #
# ### ##### #
# # #
###########E#
#S###########
#*** # #
#*##### ### #
# # # # #
# ### # # # #
# # # # #
# # # # #
# # # #
### #########
# # #
# ### ##### #
# # #
###########E#
As you can see, it comes this way but while returning it doesn't remove stars correctly.
How can I solve this bug?