-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolver.java
94 lines (78 loc) · 1.91 KB
/
Solver.java
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.Comparator;
public class Solver {
private Board initial;
private MinPQ<Board> pq;
private MinPQ<Board> tpq;
private Queue<Board> backtrace;
private Queue<Board> tbacktrace;
private ManhattanCmp mcmp;
private int movesCount;
private int tMovesCount;
private boolean isSolvable;
public Solver(Board initial) {
this.initial = initial;
mcmp = new ManhattanCmp();
pq = new MinPQ(8, mcmp);
backtrace = new Queue<Board>();
backtrace.enqueue(initial);
movesCount = 0;
tpq = new MinPQ(8, mcmp);
tbacktrace = new Queue<Board>();
tbacktrace.enqueue(initial.twin());
tMovesCount = 0;
isSolvable = true;
doSolve();
}
private void doSolve() {
Board tmp = initial;
Board twin = initial.twin();
while (!tmp.isGoal()) {
for (Board b : tmp.neighbors())
pq.insert(b);
tmp = pq.delMin();
movesCount++;
backtrace.enqueue(tmp);
for (Board b : twin.neighbors())
tpq.insert(b);
twin = tpq.delMin();
tMovesCount++;
tbacktrace.enqueue(twin);
}
}
private class ManhattanCmp implements Comparator<Board> {
public int compare(Board v, Board w) {
if (v.manhattan() < w.manhattan())
return -1;
else if (v.manhattan() > w.manhattan())
return 1;
else
return 0;
}
}
public boolean isSolvable() {
return isSolvable;
}
public int moves() {
return movesCount;
}
public Iterable<Board> solution() {
return backtrace;
}
public static void main(String[] args) {
In in = new In(args[0]);
int N = in.readInt();
int[][] blocks = new int[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
blocks[i][j] = in.readInt();
Board initial = new Board(blocks);
Solver solver = new Solver(initial);
if (!solver.isSolvable())
StdOut.println("No solution available");
else {
StdOut.println("Minimum number of moves = " + solver.moves());
for (Board board : solver.solution())
StdOut.println(board);
}
}
}