-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolver.java
105 lines (89 loc) · 2.64 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
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.In;
import java.util.LinkedList;
import java.util.Comparator;
public class Solver {
private class Node implements Comparator<Node> {
private int manhattan;
private int hamming;
Board board;
private int moves;
private int priority;
public Node(Board b, int moves) {
board = b;
manhattan = board.manhattan();
hamming = board.hamming();
this.moves = moves;
priority = moves + manhattan;
}
public int compare(Node a, Node b) {
if (a.priority < b.priority) {
return -1;
} else if (a.priority == b.priority) {
return 0;
} else {
return 1;
}
}
public boolean isGoalNode() {
return board.isGoal();
}
public int getMoves() {
return moves;
}
}
private boolean solvable;
private int moves;
public Solver(Board initial) {
if (initial == null) {
throw new IllegalArgumentException();
}
MinPQ<Node> queue = new MinPQ<>(10);
Node node = new Node(initial, 0);
queue.insert(node);
solvable = false;
moves = 0;
while (!queue.isEmpty()) {
Node current = queue.min();
if (current.isGoalNode()) {
solvable = true;
moves = current.getMoves();
break;
}
for (Board next : current.board.neighbours()) {
// TODO if unseen
}
}
moves = -1;
}
public boolean isSolvable() {
return solvable;
}
public int moves() {
return moves;
}
public Iterable<Board> solution() {
LinkedList<Board> list = new LinkedList<>();
return list;
}
public static void main(String[] args) {
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);
}
}
}