-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sudoku Solver.java
79 lines (76 loc) · 2.22 KB
/
Sudoku 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
class Solution {
public void solveSudoku(char[][] board) {
solve(board, 0, 0);
}
private boolean solve(char[][] board, int i, int j){
if (i == board.length - 1 && j == board[0].length){
return true;
}
if (j == board[0].length){
i = i + 1;
j = 0;
}
if (board[i][j] == '.'){
for (int k = 1; k <= 9; k ++ ){
board[i][j] = (char)((int)'0' + k);
if (valid(board, i, j) == true){
boolean tmp = solve(board, i, j+1);
if (tmp == true){
return true;
}
}
}//for k
board[i][j] = '.';
}// i j
else{
return solve(board, i, j+1);
}
return false;
}
private boolean valid(char[][] board, int x, int y){
int check = 0;
for (int j = 0; j < board[0].length; j ++){
int val = board[x][j] - '0';
if (board[x][j] == '.'){
continue;
}
if ((check & (1<<(val-1))) == 1<<(val-1)){
return false;
}
else{
check = check | 1<<(val-1);
}
}
check = 0;
for (int i = 0; i < board.length; i ++){
int val = board[i][y] - '0';
if (board[i][y] == '.'){
continue;
}
if ((check & (1<<(val-1))) == 1<<(val-1)){
return false;
}
else{
check = check | 1<<(val-1);
}
}
int ib = x/3;
int jb = y/3;
check = 0;
for (int i = ib*3; i < (ib+1)*3; i ++){
for (int j = jb*3; j < (jb+1)*3; j++){
int val = board[i][j] - '0';
if (board[i][j] == '.'){
continue;
}
if ((check & (1<<(val-1))) == 1<<(val-1)){
return false;
}
else{
check = check | 1<<(val-1);
}
}
}
return true;
}
}