| 10 | import edu.princeton.cs.algs4.StdOut; |
| 11 | |
| 12 | public class Solver { |
| 13 | private final boolean solvable; |
| 14 | |
| 15 | private final int moves; |
| 16 | |
| 17 | private final Node goal; |
| 18 | |
| 19 | private class Node implements Comparable<Node> { |
| 20 | final Board board; |
| 21 | final Node prev; |
| 22 | final int moves; |
| 23 | final int manhattanScore; |
| 24 | |
| 25 | Node(Board b, Node p, int m) { |
| 26 | board = b; |
| 27 | prev = p; |
| 28 | moves = m; |
| 29 | manhattanScore = m + b.manhattan(); |
| 30 | } |
| 31 | |
| 32 | public int compareTo(Node that) { |
| 33 | return Integer.compare(this.manhattanScore, that.manhattanScore); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // find a solution to the initial board (using the A* algorithm) |
| 38 | public Solver(Board initial) { |
| 39 | if (initial == null) throw new IllegalArgumentException(); |
| 40 | MinPQ<Node> minPQ = new MinPQ<>(); |
| 41 | MinPQ<Node> minPQForTwin = new MinPQ<>(); |
| 42 | minPQ.insert(new Node(initial, null, 0)); |
| 43 | minPQForTwin.insert(new Node(initial.twin(), null, 0)); |
| 44 | MinPQ<Node> executor = minPQ; |
| 45 | Node node = null; |
| 46 | while (!executor.isEmpty()) { |
| 47 | node = executor.delMin(); |
| 48 | if (node.board.isGoal()) { |
| 49 | break; |
| 50 | } |
| 51 | Iterable<Board> neighbors = node.board.neighbors(); |
| 52 | for (Board b : neighbors) |
| 53 | if (node.prev == null || !b.equals(node.prev.board)) |
| 54 | executor.insert(new Node(b, node, node.moves + 1)); |
| 55 | |
| 56 | executor = executor == minPQ ? minPQForTwin : minPQ; |
| 57 | } |
| 58 | solvable = executor == minPQ; |
| 59 | assert node != null; |
| 60 | moves = node.moves; |
| 61 | goal = node; |
| 62 | } |
| 63 | |
| 64 | // is the initial board solvable? (see below) |
| 65 | public boolean isSolvable() { |
| 66 | return solvable; |
| 67 | } |
| 68 | |
| 69 | // min number of moves to solve initial board; -1 if unsolvable |
nothing calls this directly
no outgoing calls
no test coverage detected