Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have to write a code for a maze. I have already completed to core of it. Howev

ID: 3627460 • Letter: I

Question

I have to write a code for a maze. I have already completed to core of it. However, I can't get the backtracking portion done. It checks to see if there is a '.' in the current location if there is then move there. If it eventually reaches a deadend start over and try again with moves not already tried. I know I am missing a boolean variable or something. Can someone please help me?

public boolean solveMaze(int x, int y)
{
maze1.createPath(x,y);//places an x on current location
mazeSolve=maze1.copyArray();//makes a copy of current array

if(x == endx && y == endy)//base case this is the exit
return true;
else if (mazeSolve[x+1][y]=='.')//moves down
{
solveMaze(x+1,y);
}
else if (mazeSolve[x][y+1]=='.')//moves right
{
solveMaze(x,y+1);
}
else if (mazeSolve[x-1][y]=='.')//moves up
{
solveMaze(x-1, y);
}
else if (mazeSolve[x][y-1]=='.')//moves left
{
solveMaze(x,y-1);
}
else{
maze1.removePath(x,y);//replaces 'x' with '.'
mazeSolve=maze1.copyArray();
}


return false;

}//end recursion

Explanation / Answer

I got it to work. Here's the gist: you don't need to copy the array every time you call the method--because you reset the current space if it's a deadend, you can just use the original array. Also, you need to test that you can check a space for a '.' before you check it so that you don't get an outofbounds exception. Most importantly: when you make the recursive call, you need to encase it in an if statement, and if it returns true, then have the current method call return true as well. Does that make sense? Here's the code: Also, unless it's required, you don't need to call separate methods to place/remove an x on the current space, since it's only a one-line command: maze1[x][y] = 'x'; public boolean solveMaze(int x, int y) { createPath(x,y);//places an x on current location // char[][] mazeSolve=copyArray();//makes a copy of current array // print(); if(x == endx && y == endy){//base case this is the exit return true; } if (x 0){ if(maze1[x][y-1]=='.')//moves left { if(solveMaze(x,y-1)){ return true; } } } else{ removePath(x,y);//replaces 'x' with '.' // mazeSolve=maze1.copyArray(); } return false; }//end recursion