-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path037_Sudoku_Solver.cpp
59 lines (58 loc) · 1.73 KB
/
037_Sudoku_Solver.cpp
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
class Solution {
private:
int box3_3[9][9] = {0};
int box_ver[9][9] = {0};
int box_hor[9][9] = {0};
int find(vector<vector<char>> &board, int n) {
if (n == 81) {
return 1;
}
int i = n / 9;
int j = n % 9;
if (board[i][j] == '.') {
for (int k = 0; k < 9; k++) {
if (!(box3_3[(i / 3) * 3 + (j / 3)][k] | box_ver[j][k] | box_hor[i][k])) {
board[i][j] = char('1' + k);
box3_3[(i / 3) * 3 + (j / 3)][k] = 1;
box_ver[j][k] = 1;
box_hor[i][k] = 1;
n ++;
if (find(board, n) == 1) {
return 1;
} else {
n --;
i = n / 9;
j = n % 9;
board[i][j] = '.';
box3_3[(i / 3) * 3 + (j / 3)][k] = 0;
box_ver[j][k] = 0;
box_hor[i][k] = 0;
}
}
}
return 0;
} else {
n ++;
if (find(board, n) == 1) {
return 1;
} else {
n --;
return 0;
}
}
}
public:
void solveSudoku(vector<vector<char>>& board) {
for (int i = 0; i < 9; i ++) {
for (int j = 0; j < 9; j ++) {
if (board[i][j] != '.') {
int num = board[i][j] - '1';
box3_3[(i / 3) * 3 + (j / 3)][num] = 1;
box_ver[j][num] = 1;
box_hor[i][num] = 1;
}
}
}
find(board, 0);
}
};