-
Notifications
You must be signed in to change notification settings - Fork 0
/
#0037.sudoku-solver.cpp
47 lines (42 loc) · 1.24 KB
/
#0037.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
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
recursive(board, 0, 0);
}
private:
bool recursive(vector<vector<char>>& board, int row, int col) {
for (int i = row; i < 9; ++i, col = 0) {
for (int j = col; j < 9; ++j) {
if (board[i][j] != '.') {
continue;
}
for (char d = '1'; d <= '9'; ++d) {
if(!isValid(board, i, j, d)) {
continue;
}
board[i][j] = d;
if (recursive(board, i, j + 1)) {
return true;
}
board[i][j] = '.';
}
return false;
}
}
return true;
};
bool isValid(vector<vector<char>>& board, int row, int col, char c) {
for (int i = 0; i < 9; ++i) {
if (board[i][col] == c) {
return false;
}
if( board[row][i] == c) {
return false;
}
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
return false;
}
}
return true;
};
};