Like many other java students in college, I need to develop a maze program that solves the maze. My solveMaze method, which implements recursion, returned a stackoverflow runtime error. How to solve this problem please? Is this related to my algorithm? Thanks in advance.
A) I created a labyrinth of solutions that will contain the path to the exit.
B) Then I implemented the solveMaze () method, which each step took a step to the exit.
Note. The isWall () method checks if the position you are moving to is a wall or not.
public void showPath(){
int[][] sol = new int[m.length][m[0].length];
for (int j = 0; j < sol.length; j++) {
for (int i = 0; i < sol[0].length; i++) {
sol[j][i] = m[j][i];
}
}
if(solveMaze(sol, m.length-1, 0, exitCords)==false)
System.out.println("Solution doesn't exist");
else{
for (int y = 0; y < sol.length; y++) {
for (int x = 0; x < sol[0].length; x++) {
if(sol[y][x] == exitCords[0] && sol[y][x] == exitCords[1]){
System.out.print("E ");
}
else{
if(sol[y][x]==1)
{
System.out.print(" ");
}
else if(sol[y][x]==3)
{
System.out.print("~");
}
else {
System.out.print("# ");
}
}
}
System.out.println();
}
}}
public boolean solveMaze(int[][] sol, int y, int x, int[] exitCords){
if(y==exitCords[1]&&x==exitCords[0]){
return true;
}
if(!isWall(x, y-1)&&sol[y-1][x]!=3){
sol[y][x]=3;
y--;
sol[y][x]=3;
solveMaze(sol, y, x, exitCords);
return true;
}
else if(!isWall(x, y+1)&&sol[y+1][x]!=3){
sol[y][x] =3;
y++;
sol[y][x]=3;
solveMaze(sol, y, x, exitCords);
return true;
}
else if(!isWall(x+1, y) &&sol[y][x+1]!=3){
sol[y][x]=3;
x++;
sol[y][x]=3;
solveMaze(sol, y, x, exitCords);
return true;
}
else if(!isWall(x-1, y)&&sol[y][x-1]!=3){
sol[y][x] =3;
x--;
sol[y][x]=3;
solveMaze(sol, y, x, exitCords);
return true;
}
else if((isWall(x, y-1) && isWall(x, y+1) && isWall(x+1, y)) || (isWall(x, y-1) && isWall(x, y+1) && isWall(x-1, y))
|| (isWall(x-1, y) && isWall(x, y+1) && isWall(x+1, y)) ||(isWall(x-1, y) && isWall(x, y-1) && isWall(x+1, y))){
if(isWall(x, y-1) && isWall(x, y+1) && isWall(x+1, y)){
sol[y][x]=0;
solveMaze(sol, y, x-1, exitCords);
return true;
}
if(isWall(x, y-1) && isWall(x, y+1) && isWall(x-1, y)){
sol[y][x]=0;
solveMaze(sol, y, x+1, exitCords);
return true;
}
if(isWall(x-1, y) && isWall(x, y+1) && isWall(x+1, y)){
sol[y][x]=0;
solveMaze(sol, y-1, x, exitCords);
return true;
}
if(isWall(x-1, y) && isWall(x, y-1) && isWall(x+1, y)){
sol[y][x]=0;
solveMaze(sol, y+1, x, exitCords);
return true;
}
}
return false;
}