-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.java
124 lines (95 loc) · 4 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
public class Solver {
private class Move implements Comparable<Move> {
public Board board;
public int moves;
public Move prev;
public int man;
public Move(Board b) {
this.board = b;
moves = 0;
prev = null;
man = board.manhattan();
}
public Move(Board b, Move previous) {
board = b;
prev = previous;
moves = previous.moves + 1;
man = board.manhattan();
}
public int compareTo(Move that) {
return (this.man + this.moves) - (that.man + that.moves);
}
}
private Move lastMove;
// find a solution to the initial board (using the A* algorithm)
public Solver(Board initial) {
if (initial == null)
throw new IllegalArgumentException("argument to constructor is null");
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 = game(moves);
if (lastMove != null || game(twinMoves) != null)
break;
}
}
private Move game(MinPQ<Move> moves) {
Move bestMove = moves.delMin();
if (bestMove.board.isGoal()) {
return bestMove;
}
for (Board i : bestMove.board.neighbors()) {
if (bestMove.prev == null || !i.equals(bestMove.prev.board))
moves.insert(new Move(i, bestMove));
}
return null;
}
// is the initial board solvable? (see below)
public boolean isSolvable() {
return lastMove != null;
}
// min number of moves to solve initial board
public int moves() {
if (this.isSolvable())
return lastMove.moves;
return -1;
}
// sequence of boards in a shortest solution
public Iterable<Board> solution() {
if (!this.isSolvable())
return null;
Stack<Board> solution = new Stack<Board>();
while (lastMove != null) {
solution.push(lastMove.board);
lastMove = lastMove.prev;
}
return solution;
}
// test client (see below)
public static void main(String[] args) {
// create initial board from file
In in = new In(args[0]);
int n = in.readInt();
int[][] tiles = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
tiles[i][j] = in.readInt();
Board initial = new Board(tiles);
// solve the puzzle
Solver solver = new Solver(initial);
// print solution to standard output
if (!solver.isSolvable())
StdOut.println("No solution possible");
else {
StdOut.println("Minimum number of moves = " + solver.moves());
for (Board board : solver.solution())
StdOut.println(board);
}
}
}