Ejemplo n.º 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;
  }
Ejemplo n.º 2
0
  /**
   * return a COPY of solution. This should be : [x1,y1,x2,y2,x3,y3...] the coordinates of the
   * solution from start to end. Precondition : one of the solveXXX methods has already been called
   * (solveBFS OR solveDFS OR solveAStar) (otherwise an empty array is returned) Postcondition: the
   * correct solution is in the returned array
   */
  public int[] solutionCoordinates() {
    MyQueue<Integer> listOfInts = new MyQueue<Integer>();
    Node current = placesToGo.next();
    while (current != null) {
      listOfInts.enqueue(current.getValue()[0]);
      listOfInts.enqueue(current.getValue()[1]);
      current = current.getPrev();
    }

    solution = new int[listOfInts.size()];
    for (int i = 0; i < solution.length; i++) {
      solution[i] = listOfInts.dequeue();
    }

    return solution;
  }
Ejemplo n.º 3
0
  private ArrayList<Node> getNeighbors(Node current) {
    int row = current.getValue()[0];
    int col = current.getValue()[1];
    ArrayList<Node> neighbors = new ArrayList<Node>();

    if (maze[row + 1][col] == ' ' || maze[row + 1][col] == 'E') {
      neighbors.add(new Node(row + 1, col, current));
    }
    if (maze[row - 1][col] == ' ' || maze[row - 1][col] == 'E') {
      neighbors.add(new Node(row - 1, col, current));
    }
    if (maze[row][col + 1] == ' ' || maze[row][col + 1] == 'E') {
      neighbors.add(new Node(row, col + 1, current));
    }
    if (maze[row][col - 1] == ' ' || maze[row][col - 1] == 'E') {
      neighbors.add(new Node(row, col - 1, current));
    }
    return neighbors;
  }