-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.java
83 lines (74 loc) · 1.8 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
public class Solver {
public int[][] board;
public Solver(int[][] board) {
this.board = board;
}
public int[] getEmpty() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == 0) {
int[] coords = {i, j};
return coords;
}
}
}
int[] coords = {-1, -1};
return coords;
}
public boolean validator(int[] coords, int value) {
int y = coords[0];
int x = coords[1];
int boxSize = (board.length + 2)/3;
for (int i = 0; i < board.length; i++) {
if (board[i][x] == value || board[y][i] == value) {
return false;
}
}
for (int j = 0; j < boxSize; j++) {
for (int k = 0; k < boxSize; k++) {
if (board[boxSize * (y / boxSize) + (j+y)%boxSize][boxSize * (x / boxSize) + (k+x)%boxSize] == value) {
return false;
}
}
}
return true;
}
public boolean sudokuSolver() {
if (getEmpty()[0] != -1) {
int[] coords = getEmpty();
for (int i = 1; i < board.length + 1; i++) {
if (validator(coords, i)) {
setBoard(coords, i);
if (!sudokuSolver()) {
setBoard(coords, 0);
}
}
}
return board[coords[0]][coords[1]] != 0;
}
return true;
}
public void setBoard(int[] coords, int value) {
board[coords[0]][coords[1]] = value;
}
public String toString() {
String print = "";
int boxSize = (board.length + 2) / 3;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
print += " " + board[i][j];
if (boxSize - (j%boxSize) == 1){
print += " | ";
}
}
print += "\n";
if (boxSize - (i%boxSize) == 1) {
for (int k = 0; k < board.length + boxSize; k++) {
print += "- ";
}
print += "\n";
}
}
return print;
}
}