题目链接
http://poj.org/problem?id=3074
分析
用二进制数来表示可选填的数,每次扫描找可选数最小的填。
AC代码
#include <cstdio>
const int maxn = 15;
int r[maxn], c[maxn], p[maxn], cnt[1 << 10], num[1 << 10];
char s0[maxn * maxn], s[maxn][maxn];
inline int pos(int x, int y) {
return x / 3 * 3 + y / 3;
}
inline void change(int x, int y, int k) {
r[x] ^= 1 << (k - 1);
c[y] ^= 1 << (k - 1);
p[pos(x, y)] ^= 1 << (k - 1);
}
int dfs(int tot) {
if (!tot) return 1;
int minc = 10, x, y;
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j) {
if (s[i][j] != '.') continue;
int state = r[i] & c[j] & p[pos(i, j)];
if (!state) return 0;
if (cnt[state] < minc)
minc = cnt[state], x = i, y = j;
}
int state = r[x] & c[y] & p[pos(x, y)];
while (state) {
int k = num[state & (-state)] + 1;
state -= state & (-state);
s[x][y] = k + '0';
change(x, y, k);
if (dfs(tot - 1)) return 1;
s[x][y] = '.';
change(x, y, k);
}
return 0;
}
int main() {
for (int i = 0; i < 1 << 9; ++i)
for (int j = i; j; j -= j & (-j)) ++cnt[i];
for (int i = 0; i < 9; ++i) num[1 << i] = i;
while (~scanf("%s", s0) && s0[0] != 'e') {
int tot = 0;
for (int i = 0; i < 9; ++i) r[i] = c[i] = p[i] = (1 << 9) - 1;
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j) {
s[i][j] = s0[i * 9 + j];
if (s[i][j] == '.') ++tot;
else change(i, j, s[i][j] - '0');
}
dfs(tot);
for (int i = 0; i < 9; ++i) printf("%s", s[i]);
puts("");
}
return 0;
}