选择分支最少的格子
不能与行, 列, 九宫格有重复
位运算优化
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 9, M = 1 << N;
int ones[M], map[M];
int row[N], col[N], cell[3][3];
char str[100];
void init() {
for (int i = 0; i < N; i++)
row[i] = col[i] = (1 << N) - 1;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
cell[i][j] = (1 << N) - 1;
}
void draw(int x, int y, int t, bool is_set) {
//is_set=true, make (x, y) = t
if (is_set) str[x * N + y] = '1' + t;
else str[x * N + y] = '.';
int v = 1 << t;
if (!is_set) v = -v;
//is_set=true, (x, y) 中 t已经不能用了
//is_set=false, (x, y) 中 t可以用,row, col, cell 加入1
row[x] -= v;
col[y] -= v;
cell[x / 3][y / 3] -= v;
}
int lowbit(int x) {
return x & -x;
}
int get(int x, int y) {
return row[x] & col[y] & cell[x / 3][y / 3];
}
bool dfs(int cnt) {
if (!cnt) return true;
int minv = 10;
int x, y;
// 找出分支最少的格子
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (str[i * N + j] == '.') {
int state = get(i, j);
if (ones[state] < minv) {
minv = ones[state];
x = i, y = j;
}
}
int state = get(x, y);
for (int i = state; i; i -= lowbit(i)) {
// 100100100
// 依次获取100, 10000, 1000000
int t = map[lowbit(i)];
draw(x, y, t, true);
if (dfs(cnt - 1)) return true;
draw(x, y, t, false);
}
return false;
}
int main() {
// log(1<<i) = i
for (int i = 0; i < N; i++) map[1 << i] = i;
// 0-80, 在二进制中1的个数
for (int i = 0; i < 1 << N; i++)
for (int j = 0; j < N; j++)
ones[i] += i >> j & 1;
while (cin >> str, str[0] != 'e') {
init();
int cnt = 0;
for (int i = 0, k = 0; i < N; i++)
for (int j = 0; j < N; j++, k++)
if (str[k] != '.') {
int t = str[k] - '1';
draw(i, j, t, true);
} else cnt++;
dfs(cnt);
puts(str);
}
return 0;
}