-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy path37.Sudoku Solver.cpp
52 lines (52 loc) · 1.32 KB
/
37.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
class Solution
{
public:
bool check(int i, int j, int k, vector<vector<char>> &board)
{
for (int p = 0; p < 9; p++)
{
if (board[i][p] - '0' == k)
return false;
if (board[p][j] - '0' == k)
return false;
}
int x = i / 3 * 3, y = j / 3 * 3;
for (int p = x; p < x + 3; p++)
{
for (int r = y; r < y + 3; r++)
{
if (board[p][r] - '0' == k)
return false;
}
}
return true;
}
bool solve(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++)
{
if (check(i, j, k, board))
{
board[i][j] = '0' + k;
if (solve(board))
return true;
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char>> &board)
{
solve(board);
}
};