Example #1
0
  /**
   * Computes all of the states immediately reachable from this state and returns them as an array
   * of states. You probably will not need to use this method directly, since ordinarily you will be
   * expanding <tt>Node</tt>s, not <tt>State</tt>s.
   */
  public State[] expand() {
    int gridsize = puzzle.getGridSize();
    int grid[][] = getGrid();
    int num_cars = puzzle.getNumCars();

    ArrayList<State> new_states = new ArrayList<State>();

    for (int v = 0; v < num_cars; v++) {
      int p = varPos[v];
      int fp = puzzle.getFixedPosition(v);
      boolean orient = puzzle.getCarOrient(v);
      for (int np = p - 1; np >= 0 && (orient ? grid[fp][np] : grid[np][fp]) < 0; np--) {
        int[] newVarPos = (int[]) varPos.clone();
        newVarPos[v] = np;
        new_states.add(new State(puzzle, newVarPos));
      }

      int carsize = puzzle.getCarSize(v);
      for (int np = p + carsize;
          (np < gridsize && (orient ? grid[fp][np] : grid[np][fp]) < 0)
              || (v == 0 && np == gridsize);
          np++) {
        int[] newVarPos = (int[]) varPos.clone();
        newVarPos[v] = np - carsize + 1;
        new_states.add(new State(puzzle, newVarPos));
      }
    }

    puzzle.incrementSearchCount(new_states.size());

    return (State[]) new_states.toArray(new State[0]);
  }
Example #2
0
  /**
   * Computes a grid representation of the state. In particular, an nxn two-dimensional integer
   * array is computed and returned, where n is the size of the puzzle grid. The <tt>(i,j)</tt>
   * element of this grid is equal to -1 if square <tt>(i,j)</tt> is unoccupied, and otherwise
   * contains the index of the car occupying this square. Note that the grid is recomputed each time
   * this method is called.
   */
  public int[][] getGrid() {
    int gridsize = puzzle.getGridSize();
    int grid[][] = new int[gridsize][gridsize];

    for (int i = 0; i < gridsize; i++) for (int j = 0; j < gridsize; j++) grid[i][j] = -1;

    int num_cars = puzzle.getNumCars();

    for (int v = 0; v < num_cars; v++) {
      boolean orient = puzzle.getCarOrient(v);
      int size = puzzle.getCarSize(v);
      int fp = puzzle.getFixedPosition(v);
      if (v == 0 && varPos[v] + size > gridsize) size--;
      if (orient) {
        for (int d = 0; d < size; d++) grid[fp][varPos[v] + d] = v;
      } else {
        for (int d = 0; d < size; d++) grid[varPos[v] + d][fp] = v;
      }
    }
    return grid;
  }