Я пытался создать алгоритм решения лабиринта в java. Я пытался сделать это с помощью возвратной рекурсии. Вот мой код:
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;
}
и вот основной метод:
String[][] maze = {{"#","S","#","#","#","#","#","#","#","#","#","#","#"},
{"#"," "," "," "," "," ","#"," "," "," "," "," ","#"},
{"#"," ","#","#","#","#","#"," ","#","#","#"," ","#"},
{"#"," "," "," "," "," ","#"," ","#"," ","#"," ","#"},
{"#"," ","#","#","#"," ","#"," ","#"," ","#"," ","#"},
{"#"," "," "," ","#"," ","#"," "," "," ","#"," ","#"},
{"#"," "," "," ","#"," ","#"," "," "," ","#"," ","#"},
{"#"," ","#"," ","#"," "," "," "," "," "," "," ","#"},
{"#","#","#"," ","#","#","#","#","#","#","#","#","#"},
{"#"," "," "," ","#"," "," "," "," "," "," "," ","#"},
{"#"," ","#","#","#"," ","#","#","#","#","#"," ","#"},
{"#"," "," "," "," "," ","#"," "," "," "," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#","#","E","#"}};
solver(maze,1,1);
Этот алгоритм может решить лабиринт, но есть ошибка в этом коде, и я не смог ее исправить.
Вывод:
#S###########
#*****# #
# ##### ### #
# # # # #
# ### # # # #
# # # # #
# # # # #
# # # #
### #########
# # #
# ### ##### #
# # #
###########E#
#S###########
#*** # #
#*##### ### #
# # # # #
# ### # # # #
# # # # #
# # # # #
# # # #
### #########
# # #
# ### ##### #
# # #
###########E#
Как вы можете видеть, это происходит таким образом, но при возврате не удаляет звезды правильно.
Как я могу решить эту ошибку?