I am having trouble with a recursive Java program and currently the problem is that I do not understand is why the base case1 if is executing. In the initial method call to findPath, the values 2 and 0 are being passed. exitRow = 4 and cols-1 = 11. So, my understanding is that this base case should not enter the if statement first thing since the two locations in maze[][] are not the same (maze[4][11] != maze[2][0]). But that is exactly what it is doing. I obviously have missed something in my understanding of the if structure or I have an error elsewhere and would appreciate some help.
Note: I also tried
if (row == exitRow && col == cols-1)
but this ended up giving me a stack overflow. And from what little I understand about that, it means that either my recursion is not bringing me closer to the base case or the base case is unreachable because of the way it is written. I am assuming that my recursion is correct based on this guide http://www.cs.bu.edu/teaching/alg/maze/ that I have been using. Which leads me to believe that the base case is the issue.
Many thanks.
private Boolean findPath(int row, int col)
{
//base case 1
if (maze[exitRow][cols-1]==maze[row][col])
{
System.out.println("test");//for debugging
return true;
}
//base case 2
if (maze[row][col] == '#')
{
return false;
}
maze[row][col] = 'O';
System.out.println("test1");//for debugging
steps++;
//check north
if (findPath(row+1,col)==true )
{
return true;
}
//check east
if (findPath(row,col+1)==true )
{
System.out.println("test2");
return true;
}
//check south
if (findPath(row-1,col)== true)
{
return true;
}
//check west
if (findPath(row,col-1)== true)
{
return true;
}
System.out.println(steps);
maze[row][col] = '.';//unmark location
return false;
}
will return true if the current tile is of the same type as the exit tile. Since the start and the exit are both floor (
.), the function returns immediately. Stick to this:It is the correct test to see if you have found the exit. Now for the overflow:
You mark the tiles you enter as
O, but you never test the mark if it’s present, so you walk north-south-north(at this point you remark)-south… . Since you already test for a wall (if (maze[row][col] == '#')), test for eitherif (maze[row][col] != '.')if (maze[row][col] == '#' || maze[row][col] == 'O')note that you can treat both cases the same, since the effect is the same – don’t go there.