Beispiel #1
0
  /**
   * Search for the end of the maze using the frontier. Keep going until you find a solution or run
   * out of elements on the frontier.
   */
  private boolean solve() {
    Node startNode = new Node(startRow, startCol, null);
    placesToGo.add(startNode); // adding start pos to frontier
    while (placesToGo.hasNext()) {
      Node current = placesToGo.next();

      int[] xandy = current.getValue();
      int x = xandy[0];
      int y = xandy[1];
      if (maze[x][y] == 'E') {
        return true;
      }

      for (Node neigh : getNeighbors(current)) {
        placesToGo.add(neigh);
        maze[x][y] = '.';
      }

      if (animate) {
        wait(100);
        clearTerminal();
        System.out.println(toString());
      }
    }
    return false;
  }
 public boolean neighbors(Node current) {
   try {
     if (maze[current.getRow() + 1][current.getCol()] == ' ') {
       placesToGo.add(new Node(current.getRow() + 1, current.getCol(), current));
     }
     if (maze[current.getRow() - 1][current.getCol()] == ' ') {
       placesToGo.add(new Node(current.getRow() - 1, current.getCol(), current));
     }
     if (maze[current.getRow()][current.getCol() + 1] == ' ') {
       placesToGo.add(new Node(current.getRow(), current.getCol() + 1, current));
     }
     if (maze[current.getRow()][current.getCol() - 1] == ' ') {
       placesToGo.add(new Node(current.getRow(), current.getCol() - 1, current));
     }
     return true;
   } catch (IndexOutOfBoundsException e) {
     return false;
   }
 }
 /**
  * Search for the end of the maze using the frontier. Keep going until you find a solution or run
  * out of elements on the frontier.
  */
 private boolean solve() {
   Node current = new Node(startRow, startCol, null);
   placesToGo.add(current);
   while (placesToGo.hasNext()) {
     current = placesToGo.next();
     if (maze[current.getRow()][current.getCol()] == 'E') {
       return true;
     }
     neighbors(current);
     if (animate) {
       wait(100);
       toString();
     }
   }
   return false;
 }