Asking About a Cell

Before writing the search itself, let’s isolate one small question:

Can we enter cell (row, col)?

A cell can be entered if all three conditions hold:

  1. The row is inside the maze.
  2. The column is inside the maze.
  3. The cell is not a wall.

That gives us a helper method:

private static boolean isOpen(char[][] maze, int row, int col) {
  return row >= 0
      && row < maze.length
      && col >= 0
      && col < maze[0].length
      && maze[row][col] != '#';
}

We must check the row and column before reading maze[row][col]. Otherwise, a move off the edge of the maze would try to access an invalid array index.

Next, let’s isolate a second small question:

Is cell (row, col) the exit?

In our search, reaching the exit means reaching the bottom-right corner of the maze. So the check compares the row and column against the last row and last column:

private static boolean isExit(char[][] maze, int row, int col) {
  return row == maze.length - 1 && col == maze[0].length - 1;
}

These two helpers are all the search will need to ask about a single cell.