Ejemplo n.º 1
0
  /*
    Recursive Solve function:
    A solved maze has a path marked with '@' from S to E.
    The S is replaced with '@' but the 'E' is not.
    Postcondition:
      Returns true when the maze is solved,
      Returns false when the maze has no solution.
      All visited spots that were not part of the solution are changed to '.'
      All visited spots that are part of the solution are changed to '@'
  */
  private boolean solve(int x, int y) {

    if (animate) {
      System.out.println(this);
      wait(20);
    }

    // COMPLETE SOLVE
    if (maze[x][y] == 'E') {
      return true;
    }

    if (maze[x][y] == ' ') {
      maze[x][y] = '@';
      if ((isValidMove(x + 1, y) && solve(x + 1, y))
          || (isValidMove(x, y - 1) && solve(x, y - 1))
          || (isValidMove(x - 1, y) && solve(x - 1, y))
          || (isValidMove(x, y + 1) && solve(x, y + 1))) {
        return true;
      }
    }

    maze[x][y] = '.';
    return false;

    // so it compiles
  }
Ejemplo n.º 2
0
  /*
    Recursive Solve function:

    A solved maze has a path marked with '@' from S to E.
    The S is replaced with '@' but the 'E' is not.

    Postcondition:
    Returns true when the maze is solved,
    Returns false when the maze has no solution.

    All visited spots that were not part of the solution are changed to '.'
    All visited spots that are part of the solution are changed to '@'

  */
  private boolean solve(int x, int y) {
    if (animate) {
      System.out.println(this);
      wait(20);
    }

    if (maze[x][y] == '#' || maze[x][y] == '.') {
      return false;
    } else if (maze[x][y] == ' ' || maze[x][y] == 'S') {
      maze[x][y] = '@';
      if (solve(x + 1, y) || solve(x, y + 1) || solve(x, y - 1) || solve(x - 1, y)) {
        return true;
      }
      maze[x][y] = '.';
    } else if (maze[x][y] == 'E') {
      return true;
    }

    // COMPLETE SOLVE
    return false; // so it compiles
  }