[AcWing 166] 数独
作者:互联网
DFS + 剪枝 + 位运算优化
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 9, M = 1 << N;
int ones[M]; // ones[i]表示i的二进制数中1的个数
int map2[M]; // map2[i]表示log_2(i)
int row[N], col[N], cell[3][3]; // 二进制数,1代表没填数
string str;
// 将三个数组全部设置为未填数字
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;
}
// 在(x,y)位置填数字(t+1)
// is_set为true表示填,为false表示不填(用于恢复现场)
void draw(int x, int y, int t, bool is_set)
{
if (is_set)
str[x * N + y] = '1' + t;
else
str[x * N + y] = '.';
int v = 1 << t;
if (!is_set)
v = -v;
row[x] -= v;
col[y] -= v;
cell[x / 3][y / 3] -= v;
}
int get(int x, int y)
{
return row[x] & col[y] & cell[x / 3][y / 3];
}
int lowbit(int x)
{
return x & -x;
}
bool dfs(int cnt)
{
if (!cnt)
return true;
// 找到分支情况最少的格子
int minv = N + 1;
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);
// 在1的位置填数字
for (int i = state; i; i -= lowbit(i)) {
int t = map2[lowbit(i)];
draw(x, y, t, true);
if (dfs(cnt - 1))
return true;
draw(x, y, t, false);
}
return false;
}
void solve()
{
for (int i = 0; i < N; i ++)
map2[1 << i] = i;
for (int i = 0; i < 1 << N; i ++)
for (int j = 0; j < N; j ++)
ones[i] += i >> j & 1;
while (cin >> str, str != "end") {
init();
// 记录空格子的个数
int cnt = 0;
// (i,j)是二维坐标 k是一维坐标
for (int i = 0, k = 0; i < N; i ++)
for (int j = 0; j < N; j ++, k ++) {
if (str[k] != '.') {
// 将字符1-9映射到数字0-8
int t = str[k] - '1';
draw(i, j, t, true);
}
else
cnt ++;
}
dfs(cnt);
cout << str << endl;
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
标签:cnt,int,long,++,坐标,str,166,数独,AcWing 来源: https://www.cnblogs.com/wKingYu/p/16597331.html