-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path37+Sudoku Solver.cpp
More file actions
56 lines (44 loc) · 1.41 KB
/
37+Sudoku Solver.cpp
File metadata and controls
56 lines (44 loc) · 1.41 KB
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(int row, int col, char val, vector<vector<char>>& board) {
for (int i = 0; i < board.size(); ++i) {
if (board[row][i] == val) {
return false;
}
}
for (int i = 0; i < board.size(); ++i) {
if (board[i][col] == val) {
return false;
}
}
int startX = (row / 3) * 3;
int startY = (col / 3) * 3;
for (int i = startX; i < startX + 3; ++i) {
for (int j = startY; j < startY + 3; ++j) {
if (board[i][j] == val) {
return false;
}
}
}
return true;
}
bool backTracking(vector<vector<char>>& board) {
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board.size(); ++j) {
if (board[i][j] != '.') continue;
for (char k = '1'; k <= '9'; k++) {
if (isValid(i, j, k, board)) {
board[i][j] = k;
if (backTracking(board)) return true;
board[i][j] = '.';
}
}
return false;
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
backTracking(board);
}
};