-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudoku_Solver.java
More file actions
50 lines (43 loc) · 1.33 KB
/
Sudoku_Solver.java
File metadata and controls
50 lines (43 loc) · 1.33 KB
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
class Solution {
public void solveSudoku(char[][] board) {
solveSudoku(board, 0, 0);
}
public boolean solveSudoku(char[][] board, int x, int y) {
if(y == 9) return true;
if(x == 9) return solveSudoku(board, 0, y + 1);
if(board[x][y] == '.'){
for(int i = 0; i < 9; i++){
if(isValidChar(board, x, y, (char)('1' + i))){
board[x][y] = (char)('1' + i);
if(solveSudoku(board, x + 1, y)){
return true;
}
board[x][y] = '.';
}
}
return false;
}
return solveSudoku(board, x + 1, y);
}
public boolean isValidChar(char[][] board, int x, int y, char temp){
for(int i = 0; i < 9; i++){
if(i != x && board[i][y] == temp) {
return false;
}
}
for(int i = 0; i < 9; i++){
if(i != y && board[x][i] == temp) {
return false;
}
}
int a = x / 3, b = y / 3;
for(int i = 3 * a; i < 3 * a + 3; i++){
for(int j = 3 * b; j < 3 * b + 3; j++){
if(i != x && j != y && board[i][j] == temp){
return false;
}
}
}
return true;
}
}