-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudokuSolver.java
82 lines (68 loc) · 2.06 KB
/
sudokuSolver.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
class Solution {
boolean isRowSafe(char[][] board, int row, char num) {
for(int j = 0; j < 9; j++) {
if(board[row][j] == num)
return false;
}
return true;
}
boolean isColSafe(char[][] board, int col, char num) {
for(int i = 0; i < 9; i++) {
if(board[i][col] == num)
return false;
}
return true;
}
boolean isBoxSafe(char[][] board, int row, int col, char num) {
int rowStart = row - row%3;
int colStart = col - col%3;
for(int i = rowStart; i < rowStart+3; i++) {
for(int j = colStart; j < colStart+3; j++) {
if(board[i][j] == num)
return false;
}
}
return true;
}
boolean canPlaceNum(char[][] board, int row, int col, char num) {
if(!isRowSafe(board, row, num))
return false;
if(!isColSafe(board, col, num))
return false;
if(!isBoxSafe(board, row, col, num))
return false;
return true;
}
boolean sudokuSolver(char[][] board) {
int row = -1;
int col = -1;
boolean hasEmptyCell = false;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(board[i][j] == '.') {
row = i;
col = j;
hasEmptyCell = true;
break;
}
}
if(hasEmptyCell)
break;
}
if(!hasEmptyCell) {
return true;
}
for(char num = '1'; num <= '9'; num ++) {
if(canPlaceNum(board, row, col, num)) {
board[row][col] = num;
if(sudokuSolver(board))
return true;
}
board[row][col] = '.';
}
return false;
}
public void solveSudoku(char[][] board) {
sudokuSolver(board);
}
}