/
PuzzleSolver.java
101 lines (91 loc) · 2.78 KB
/
PuzzleSolver.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
public class PuzzleSolver {
private Puzzle _puzzle;
private int _count;
private String _moves;
// pre condition: _puzzle needs to exist
// post condition: saves _puzzle into the variable p, which is a Puzzle
// bigO notation: O(1)
public PuzzleSolver(Puzzle p) {
_puzzle = p;
}
// pre condition: _count needs to exist
// post condition: the private int _count is returned
// bigO notation: O(1)
public int count() {
return _count;
}
// pre condition: _moves needs to exist
// post condition: the private int _moves is returned
// bigO notation: O(1)
public String moves() {
return _moves;
}
//WE NEED TO GO OVER THIS BECAUSE IT IS SORT OF CONFUSING
// pre condition:
// post condition:
// bigO notation:
private boolean solve(int count, int last, String stack) {
if(_puzzle.isSolved())
{
if((_count == 0) || (_count > count)) {
_count = count;
_moves = stack;
}
//System.out.println(stack);
return true;
}
count++;
if((count > 31) || ((_count != 0) && (count >= _count)))
return false;
// move the one over
if(last != 2) {
if(_puzzle.move(-1, 0)) {
solve(count, 0, stack+_puzzle.emptyPos()+":");
_puzzle.move(1, 0);
}
}
// move the one to the right
if(last != 3) {
if(_puzzle.move(0, 1)) {
solve(count, 1, stack+_puzzle.emptyPos()+":");
_puzzle.move(0, -1);
}
}
// move the one below
if(last != 0) {
if(_puzzle.move(1, 0)) {
solve(count, 2, stack+_puzzle.emptyPos()+":");
_puzzle.move(-1, 0);
}
}
// move the one to the left
if(last != 1) {
if(_puzzle.move(0, -1)) {
solve(count, 3, stack+_puzzle.emptyPos()+":");
_puzzle.move(0, 1);
}
}
return false;
}
// GO OVER THE SOLVERS
// pre condition:
// post condition:
// bigO notation:
public boolean solve() {
_count = 0;
_moves = "";
solve(0, -1, "");
return _count != 0;
}
// pre condition: the tiles are shuffled and the user is going to click on tiles
// post condition: the user has clicked on a tile to move
// bigO notation: O(N^2)
public void play(PuzzlePlayer player) {
for(int i=0, s=0; i<_count; i++) {
int n = _moves.indexOf(':', s);
int p = Integer.parseInt(_moves.substring(s, n));
s = n+1;
player.puzzleMove(p);
}
}
}