-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
56 lines (54 loc) · 1.43 KB
/
solution.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
class Solution
{
public:
bool isValid(vector<vector<char> > &board, int a, int b)
{
for (int i = 0; i < 9; ++i)
{
if (i != a && board[i][b] == board[a][b])
return false;
}
for (int j = 0; j < 9; ++j)
{
if (j != b && board[a][j] == board[a][b])
return false;
}
int x = a / 3 * 3, y = b / 3 * 3;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if (x + i != a && y + j != b
&& board[x + i][y + j] == board[a][b])
return false;
}
}
return true;
}
bool solveHelper(vector<vector<char> > &board)
{
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
if (board[i][j] == '.') {
for (int k = 1; k <= 9; ++k)
{
board[i][j] = '0' + k;
if (isValid(board, i, j) && solveHelper(board))
{
return true;
}
board[i][j] = '.';
}
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char> > &board)
{
solveHelper(board);
}
};