本题为深搜
思路:分类讨论(有数没数)检查时按排,列,方格去检查
方格:(排-1)/3*3+(列/3)+1
#include <bits/stdc++.h>
using namespace std;
int a[13][20], r[15][29], l[13][30], all[13][16];
void print() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++)cout << a[i][j] << " ";
cout << endl;
}
exit(0);
}
void sudoku(int x, int y) {
if (a[x][y] != 0) {
if (x == 9 && y == 9)print();
else {
if (y == 9)sudoku(x + 1, 1);
else sudoku(x, y + 1);
}
} else {
for (int i = 1; i <= 9; i++) {
if (r[x][i] == 0 && l[i][y] == 0 && all[(x - 1) / 3 * 3 + (y - 1) / 3 + 1][i] == 0) {
r[x][i] = l[i][y] = all[(x - 1) / 3 * 3 + (y - 1) / 3 + 1][i] = 1;
a[x][y] = i;
if (x == 9 && y == 9)print();
else {
if (y == 9)sudoku(x + 1, 1);
else sudoku(x, y + 1);
}
a[x][y] = 0;
r[x][i] = l[i][y] = all[(x - 1) / 3 * 3 + (y - 1) / 3 + 1][i] = 0;
}
}
}
}
int main() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
cin >> a[i][j];
if (a[i][j] != 0)
r[i][a[i][j]] = l[a[i][j]][j] = all[(i - 1) / 3 * 3 + (j - 1) / 3 + 1][a[i][j]] = 1;
}
}
sudoku(1, 1);
return 0;
}