-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsudokuSolver.cpp
More file actions
52 lines (49 loc) · 1.42 KB
/
sudokuSolver.cpp
File metadata and controls
52 lines (49 loc) · 1.42 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
// Source: https://leetcode.com/problems/sudoku-solver/
// Author: Miao Zhang
// Date: 2021-01-08
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
dfs(board);
}
bool dfs(vector<vector<char>>& board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
for (int num = 1; num < 10; num++) {
board[i][j] = num + '0';
if (isValid(i, j, board) && dfs(board)) {
return true;
}
board[i][j] = '.';
}
return false;
}
}
}
return true;
}
bool isValid(int x, int y, vector<vector<char>>& board) {
char val = board[x][y];
board[x][y] = 'X';
for (int i = 0; i < 9; i++) {
if (board[i][y] == val) {
return false;
}
}
for (int j = 0; j < 9; j++) {
if (board[x][j] == val) {
return false;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[3 * (x / 3) + i][3 * (y / 3) + j] == val) {
return false;
}
}
}
board[x][y] = val;
return true;
}
};