Exemplo n.º 1
1
 private Queue<SearchNode> GetSolution(Board initial) {
   Queue<SearchNode> queue = new Queue<SearchNode>();
   MinPQ<SearchNode> pq = new MinPQ<SearchNode>();
   SearchNode node = new SearchNode();
   node.brd = initial;
   node.moves = 0;
   // node.priority = initial.manhattan();
   node.prev = null;
   pq.insert(node);
   SearchNode curNode = null;
   while (!pq.isEmpty()) {
     curNode = pq.delMin();
     if (curNode.brd.isGoal()) break;
     Iterable<Board> qe = curNode.brd.neighbors();
     Iterator it = qe.iterator();
     while (it.hasNext()) {
       node.brd = (Board) it.next();
       node.moves = curNode.moves + 1;
       node.prev = curNode;
       // node.priority = node.brd.manhattan();
       queue.enqueue(node);
     }
   }
   if (queue.isEmpty()) return null;
   else {
     do {
       queue.enqueue(curNode);
       curNode = curNode.prev;
     } while (curNode != null);
     return queue;
   }
 }
  /**
   * find a solution to the initial board (using the A* algorithm). Result will be stored in
   * searchNodeSolution queue;
   *
   * @param initial
   */
  public Solver(Board initial) {
    SearchNode initSearchNd = new SearchNode(initial, null);
    initialBoard = initial;
    pq.insert(initSearchNd);

    // output
    System.out.println("======Original SearchBoard==========");
    outputSN(initSearchNd);

    // find the Goal SearchNode
    while (!pq.min().board.isGoal()) {
      Stack<SearchNode> stackSNforNbrs = new Stack<SearchNode>();
      System.out.println("======NextLevel SearchBoard==========");

      // Insert all neighbors in the priority queue
      stackSNforNbrs = findNbrSearchNode(pq.delMin());
      while (stackSNforNbrs.size() != 0) {
        pq.insert(stackSNforNbrs.pop());
      }
    }

    // Trace back the search node
    SearchNode snInSolution = pq.min();
    Stack<SearchNode> stacksolution = new Stack<SearchNode>();
    while (snInSolution.prevNode != null) {
      stacksolution.push(snInSolution);
      snInSolution = snInSolution.prevNode;
    }
    stacksolution.push(initSearchNd);

    // Make it reverse order
    while (!stacksolution.isEmpty()) searchNodeSolution.enqueue(stacksolution.pop());
  }
Exemplo n.º 3
0
 public Integer deleteMedian() {
   int left = max.size();
   int right = min.size();
   if (left == right || left < right) {
     return max.delMax();
   }
   return min.delMin();
 }
Exemplo n.º 4
0
 /** Unit tests the <tt>MinPQ</tt> data type. */
 public static void main(String[] args) {
   MinPQ<String> pq = new MinPQ<String>();
   while (!StdIn.isEmpty()) {
     String item = StdIn.readString();
     if (!item.equals("-")) pq.insert(item);
     else if (!pq.isEmpty()) StdOut.print(pq.delMin() + " ");
   }
   StdOut.println("(" + pq.size() + " left on pq)");
 }
Exemplo n.º 5
0
 private void balance() {
   int left = max.size();
   int right = min.size();
   if ((left + 2) == right) {
     max.insert(min.delMin());
   } else if ((right + 2) == left) {
     min.insert(max.delMax());
   }
 }
Exemplo n.º 6
0
 public Double median() {
   int left = max.size();
   int right = min.size();
   if (left == right) {
     return (max.max() + min.min()) * 0.5;
   }
   if (left > right) {
     return max.max().doubleValue();
   }
   return min.min().doubleValue();
 }
Exemplo n.º 7
0
  // find a solution to the initial board (using the A* algorithm)
  public Solver(Board initial) {
    Board twin = initial.twin();
    SearchNode minNode = null;
    boolean isTwinRound = false;
    MinPQ<SearchNode> currentPQ = null;

    minPQ.insert(new SearchNode(initial));
    minPQForTwin.insert(new SearchNode(twin));

    while (true) {
      // Searching solution in the initial board and and its twin board
      // simultaneously(alternating in loops).
      // It has been proven by Math theory that exactly one of the two
      // will lead to the goal board. If a solution is found in the twin
      // board, it immediately proves that the initial board is not solvable,
      // and the search will terminate there.
      // Otherwise, the initial board will reach a solution.
      if (isTwinRound) {
        currentPQ = minPQForTwin;
      } else {
        currentPQ = minPQ;
      }

      minNode = currentPQ.delMin();
      if (minNode.getBoard().isGoal()) {
        break;
      } else {
        for (Board neighbor : minNode.getBoard().neighbors()) {
          // Insert the neighbors into the MinPQ if:
          // 1. Current node contains the initial board(has no prev node)
          // 2. The new neighbor is not the same as current node's previous search node.
          //    This is a critical optimization used to reduce unnecessary
          //    exploration of already visited search nodes.
          if (minNode.getPrev() == null || !neighbor.equals(minNode.getPrev().getBoard())) {
            currentPQ.insert(new SearchNode(neighbor, minNode));
          }
        }
        // Flip the state of the isTwinRound flag
        isTwinRound = isTwinRound ? false : true;
      }
    }

    if (isTwinRound) {
      isSolvable = false;
      solution = null;
    } else {
      isSolvable = true;
      solution = minNode;
      moves = solution.getMoves();
    }
  }
Exemplo n.º 8
0
 private void visit(EdgeWeightedGraph G, int v) {
   // Mark v and add to pq all edges from v to unmarked vertices.
   marked[v] = true;
   for (Edge e : G.adj(v)) {
     if (!marked[e.other(v)]) {
       pq.insert(e);
     }
   }
 }
Exemplo n.º 9
0
 KruskalMST(EdgeWeightedGraph G) {
   MinPQ<Edge> pq = new MinPQ<Edge>(); // we dont need to pass a new comparator let it
   // follow the natural ordering of edges
   double temp_wt = 0;
   for (Edge e : G.edges()) pq.insert(e);
   UF set = new UF(G.V());
   while (!pq.isEmpty() && mst.size() < (G.V() - 1)) {
     Edge e = pq.delMin();
     int v = e.either();
     int w = e.other(v);
     if (!set.connected(v, w)) {
       set.union(v, w);
       mst.add(e);
       temp_wt += e.weight();
     }
   }
   this.weight = temp_wt;
 }
Exemplo n.º 10
0
 public void insert(Integer x) {
   if (max.isEmpty()) {
     max.insert(x);
   } else if (lessOrEqual(x, max.max())) {
     max.insert(x);
   } else {
     min.insert(x);
   }
   balance();
 }
Exemplo n.º 11
0
  /**
   * Reads a sequence of transactions from standard input; takes a command-line integer M; prints to
   * standard output the M largest transactions in descending order.
   */
  public static void main(String[] args) {
    int M = Integer.parseInt(args[0]);
    MinPQ<Transaction> pq = new MinPQ<Transaction>(M + 1);

    while (StdIn.hasNextLine()) {
      // Create an entry from the next line and put on the PQ.
      String line = StdIn.readLine();
      Transaction transaction = new Transaction(line);
      pq.insert(transaction);

      // remove minimum if M+1 entries on the PQ
      if (pq.size() > M) pq.delMin();
    } // top M entries are on the PQ

    // print entries on PQ in reverse order
    Stack<Transaction> stack = new Stack<Transaction>();
    for (Transaction transaction : pq) stack.push(transaction);
    for (Transaction transaction : stack) StdOut.println(transaction);
  }
Exemplo n.º 12
0
  /**
   * Dado un grafo no dirigido y con pesos, ejecuta el algoritmo de Kruskal para la obtención del su
   * árbol de cobertura mínima.
   *
   * @param G Grafo no dirigido con pesos al cual se le deesea obtener su arbol de cobertura mínima.
   */
  public void minimumSpanningTree(EdgeWeightedGraph G) // By Kruskal's algorithm
      {
    LinkedList<Edge> mst = new LinkedList<>();

    MinPQ<Edge> pq = new MinPQ<>(G.E());
    for (Edge edge : G.edges()) // Bag<Edge> != Comparator<Edge> :c
    pq.insert(edge);

    UF uf = new UF(G.V());

    while (!pq.isEmpty() && mst.size() < G.V() - 1) {
      Edge edge = pq.delMin();
      int v = edge.either(), w = edge.other(v);

      if (!uf.connected(v, w)) {
        uf.union(v, w);
        mst.add(edge);
      }
    }

    System.out.println("");
    for (Edge edge : mst) System.out.println(edge);
  }
Exemplo n.º 13
0
  // Kruskal's algorithm
  public KruskalMST(EdgeWeightedGraph G) {
    // more efficient to build heap by passing array of edges
    MinPQ<Edge> pq = new MinPQ<Edge>();
    for (Edge e : G.edges()) {
      pq.insert(e);
    }

    // run greedy algorithm
    UF uf = new UF(G.V());
    while (!pq.isEmpty() && mst.size() < G.V() - 1) {
      Edge e = pq.delMin();
      int v = e.either();
      int w = e.other(v);
      if (!uf.connected(v, w)) { // v-w does not create a cycle
        uf.union(v, w); // merge v and w components
        mst.enqueue(e); // add edge e to mst
        weight += e.weight();
      }
    }

    // check optimality conditions
    assert check(G);
  }
Exemplo n.º 14
0
  public LazyPrimMST(EdgeWeightedGraph G) {
    pq = new MinPQ<Edge>();
    marked = new boolean[G.V()];
    mst = new Queue<Edge>();

    visit(G, 0); // assumes G is connected (see ex. 4.3.22)
    while (!pq.isEmpty()) {
      Edge e = pq.delMin(); // Get lowest-weight from pq.
      int v = e.either();
      int w = e.other(v);
      if (marked[v] && marked[w]) {
        continue; // Skip if ineligible
      }
      mst.enqueue(e); // Add edge to tree
      if (!marked[v]) { // Add vertex to tree (either v or w).
        visit(G, v);
      }

      if (!marked[w]) {
        visit(G, w);
      }
    }
  }
Exemplo n.º 15
0
  private void solveInternal(MinPQ<SearchNode> queue, boolean twin) {

    while (!queue.isEmpty() && solvable == null) {

      //            StdOut.println("Queue size = "+queue.size());
      SearchNode min = queue.delMin();
      //            StdOut.println("Manhatan + moves = "+(min.board.manhattan()+min.moves));
      if (min.board.isGoal()) {
        if (twin) {
          solvable = false;
        } else {
          solution = min;
          solvable = true;
        }
        return;
      } else {
        for (Board n : min.board.neighbors()) {
          if (min.previous == null || (!n.equals(min.previous.board))) {
            queue.insert(new SearchNode(n, min, min.moves + 1));
          }
        }
      }
    }
  }
Exemplo n.º 16
0
 public boolean isEmpty() {
   return min.isEmpty() && max.isEmpty();
 }
Exemplo n.º 17
0
 public Key next() {
   if (!hasNext()) throw new NoSuchElementException();
   return copy.delMin();
 }
Exemplo n.º 18
0
 public boolean hasNext() {
   return !copy.isEmpty();
 }
Exemplo n.º 19
0
 // add all items to copy of heap
 // takes linear time since already in heap order so no keys move
 public HeapIterator() {
   if (comparator == null) copy = new MinPQ<Key>(size());
   else copy = new MinPQ<Key>(size(), comparator);
   for (int i = 1; i <= N; i++) copy.insert(pq[i]);
 }