题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
我也是dfs+回溯+剪枝,各位看看我判定局面的思路即可
// https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 5 + 9;
int a[maxn][maxn];
const int sx[] = {0, 1, 1, 1, 4, 4, 4, 7, 7, 7};
const int sy[] = {0, 1, 4, 7, 1, 4, 7, 1, 4, 7};
bool inside(int x, int y) { return 1 <= x && x <= 9 && 1 <= y && y <= 9; }
bool accept() {
static int cnt[10][10][3]; // row, col, squared
memset(cnt, 0, sizeof(cnt)); // 第 s 个九宫格
for (int s = 1; s <= 9; ++s) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int x = sx[s] + i, y = sy[s] + j;
if (a[x][y] == 0) continue;
if (++cnt[a[x][y]][x][0] > 1) return false;
if (++cnt[a[x][y]][y][1] > 1) return false;
if (++cnt[a[x][y]][s][2] > 1) return false;
}
}
}
return true;
}
void dfs(int x, int y) {
if (x == 9 && y > 9) { // find ans
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
cout << a[i][j] << ' ';
}
cout << endl;
}
exit(0);
}
if (!inside(x, y)) {
dfs(x + 1, 1);
return;
}
if (a[x][y] != 0) {
dfs(x, y + 1);
return;
}
// a[x][y] == 0, inside(x, y)
for (int i = 1; i <= 9; ++i) {
a[x][y] = i;
if (accept()) dfs(x, y + 1);
a[x][y] = 0;
}
}
int main() {
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
cin >> a[i][j];
}
}
dfs(1, 1);
}
查看12道真题和解析