-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path37. Sudoku Solver.cpp
84 lines (76 loc) · 1.98 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*Sudoku Solver:Write a program to solve a Sudoku puzzle by filling the empty cells.Empty cells are indicated by the character '.'.*/
//标准递归回溯问题
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
auto &a = board;
n = a.size();
if (n == 0) {
return;
}
nr = (int)sqrt(n);
ns = n * n;
row.resize(n, 0);
col.resize(n, 0);
block.resize(n, 0);
int i, j;
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
if (a[i][j] == '.') {
pos.push_back(i * n + j);
} else {
mark(i, j, a[i][j] - '0');
}
}
}
bool suc = dfs(a);
row.clear();
col.clear();
block.clear();
pos.clear();
n = nr = ns = 0;
}
private:
int n, nr, ns;
vector<int> row, col, block;
vector<int> pos;
void mark(int x, int y, int d) {
int bt = (1 << d - 1);
row[x] ^= bt;
col[y] ^= bt;
block[x / nr * nr + y / nr] ^= bt;
}
bool dfs(vector<vector<char>> &a) {
if (pos.size() == 0) {
// Done
return true;
}
int idx = pos.back();
int x = idx / n;
int y = idx % n;
int d;
int bt;
for (d = 1; d <= n; ++d) {
bt = (1 << d - 1);
if (row[x] & bt) {
continue;
}
if (col[y] & bt) {
continue;
}
if (block[x / nr * nr + y / nr] & bt) {
continue;
}
pos.pop_back();
mark(x, y, d);
a[x][y] = d + '0';
if (dfs(a)) {
return true;
}
a[x][y] = '.';
mark(x, y, d);
pos.push_back(idx);
}
return false;
}
};