Maze Helpers and Edge Cases

The maze is a char[][]. A cell holding '#' is a wall; any other character is an open cell. The start is the top-left cell, (0, 0), and the exit is the bottom-right cell. From a cell, one move goes up, right, down, or left by one cell. A move may not leave the maze or enter a wall. The search answers one question: is there a path from the start to the exit?

For example, this array:

char[][] maze = {
  {'S', '.', '#'},
  {'.', '.', 'E'}
};

is this maze, where █ is a wall:

┌───┬───┬───┐
│ S │   │ █ │
├───┼───┼───┤
│   │   │ E │
└───┴───┴───┘
Solution
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] != '#';
}
Solution
private static boolean isExit(char[][] maze, int row, int col) {
  return row == maze.length - 1 && col == maze[0].length - 1;
}
Solution

It reads maze[row][col] before checking that row and col are inside the maze. The search calls isOpen on positions outside the maze, such as (0, -1) or (maze.length, 0), and on those the read throws an ArrayIndexOutOfBoundsException. The bounds checks must come first so that && short-circuits before the read.

Solution
  • The start is a wall: false, without exploring anything.
  • The exit is a wall: false; the search may explore the reachable open cells but never enters the exit.
  • The maze is a single open cell: true, since the start is the exit.