-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolver.java
More file actions
74 lines (60 loc) · 1.96 KB
/
Solver.java
File metadata and controls
74 lines (60 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.Stack;
/**
* Created by merlin on 17/2/19.
*/
public class Solver {
private class Move implements Comparable<Move> {
private Move previous;
private Board board;
private int numMoves = 0;
public Move(Board board) {
this.board = board;
}
public Move(Board board, Move previous) {
this.board = board;
this.previous = previous;
this.numMoves = previous.numMoves + 1;
}
public int compareTo(Move move) {
return (this.board.manhattan() - move.board.manhattan()) + (this.numMoves - move.numMoves);
}
}
private Move lastMove;
public Solver(Board initial) {
MinPQ<Move> moves = new MinPQ<Move>();
moves.insert(new Move(initial));
MinPQ<Move> twinMoves = new MinPQ<Move>();
twinMoves.insert(new Move(initial.twin()));
while(true) {
lastMove = expand(moves);
if (lastMove != null || expand(twinMoves) != null) return;
}
}
private Move expand(MinPQ<Move> moves) {
if(moves.isEmpty()) return null;
Move bestMove = moves.delMin();
if (bestMove.board.isGoal()) return bestMove;
for (Board neighbor : bestMove.board.neighbors()) {
if (bestMove.previous == null || !neighbor.equals(bestMove.previous.board)) {
moves.insert(new Move(neighbor, bestMove));
}
}
return null;
}
public boolean isSolvable() {
return (lastMove != null);
}
public int moves() {
return isSolvable() ? lastMove.numMoves : -1;
}
public Iterable<Board> solution() {
if (!isSolvable()) return null;
Stack<Board> moves = new Stack<Board>();
while(lastMove != null) {
moves.push(lastMove.board);
lastMove = lastMove.previous;
}
return moves;
}
}