Once this is instantiated and method traverse(0,0) is invoked, it will automatically solve the maze showing 7 as the path and 3 as "tried paths". I'm trying to understand this code but I get stuck at the first else statement in the traverse method.
public class Maze
{
private final int TRIED = 3;
private final int PATH = 7;
private int[][] grid = { {1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1,0,0,1},
{0,0,0,0,1,0,1,0,1,0,1,0,0},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1} };
public boolean traverse (int row, int column)
{
boolean done = false;
if (valid (row, column))
{
grid[row][column] = TRIED;
// this cell has been tried
if (row == grid.length-1 && column == grid[0].length-1)
done = true;
// the maze is solved
else
{
done = traverse (row+1, column);
// down
if (!done)
done = traverse (row, column+1);
// right
if (!done)
done = traverse (row-1, column);
// up
if (!done)
done = traverse (row, column-1);
// left
}
if (done)
// this location is part of the final path
grid[row][column] = PATH;
}
return done;
}
//-----------------------------------------------------------------
// Determines if a specific location is valid.
//-----------------------------------------------------------------
private boolean valid (int row, int column)
{
boolean result = false;
// check if cell is in the bounds of the matrix
if (row >= 0 && row < grid.length && column >= 0 &&
column < grid[row].length)
// check if cell is not blocked and not previously tried
if (grid[row][column] == 1)
result = true;
return result;
}
To my knowledge,
done = traverse (row+1, column);
This line is a recursive call and will move it down once, and will run the method again but what if it's not valid? Doesn't the whole method stop? I don't understand where the flow of control shifts after a certain spot is not valid.
For example, if [1][0] is not valid, does the control shift back to the [0][0] call and process the "going right" statement? Where and what does it mean by if (!done), i mean done only equals true when the maze is completely solved and if it is valid, done will equal true, so wouldn't the whole thing just stop?