-
Notifications
You must be signed in to change notification settings - Fork 0
/
Move.java
75 lines (57 loc) · 1.59 KB
/
Move.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
import java.lang.RuntimeException;
import java.util.List;
import java.util.LinkedList;
public class Move implements AutoCloseable {
private final EmptyCell ecell;
private final Value value;
private List<ChangePossible> cp;
private SudokuBoard sudokuBoard;
public Move(SudokuBoard sudokuBoard,EmptyCell ecell,Value value) {
if(ecell.getX() != value.getX() || ecell.getY() != value.getY()) {
throw new RuntimeException("illegal state");
}
this.ecell = ecell;
this.value = value;
this.sudokuBoard = sudokuBoard;
sudokuBoard.setCell(ecell.getX(),ecell.getY(),value);
List<Cell> cells = sudokuBoard.getAffectingCells(ecell);
cp = new LinkedList<>();
for(Cell e:cells) {
if(e instanceof EmptyCell) {
ChangePossible newCp = ChangePossible.getChangePossible((EmptyCell)e,value.getValue());
if (newCp != null) {
cp.add(newCp);
}
}
}
}
public void revert() {
sudokuBoard.setCell(ecell.getX(),ecell.getY(),ecell);
for(ChangePossible e : cp) {
e.revert();
}
}
private static class ChangePossible {
EmptyCell cell;
int possibleValue;
private ChangePossible(EmptyCell cell,int possibleValue) {
this.cell = cell;
this.possibleValue = possibleValue;
}
public void revert() {
if(!cell.setPossibleValue(possibleValue)) {
throw new RuntimeException("Illegal state");
}
}
public static ChangePossible getChangePossible(EmptyCell cell,int possibleValue) {
if(cell.setNotPossibleValue(possibleValue)) {
return new ChangePossible(cell,possibleValue);
} else {
return null;
}
}
}
public void close() {
revert();
}
}