acwing 166数独
问题
传送门
代码
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int N = 9;
int ones[1<<N],map[1<<N];
int row[N],col[N],cell[N/3][N/3];
char str[100];
int lowbit(int x)
{
return x&(-x);
}
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;
}
}
}
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 minn = 10,x,y;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(str[i*9+j]=='.')
{
int cnt = ones[get(i,j)];
if(minn>cnt)
{
minn = cnt;
x = i;
y = j;
}
}
}
}
for(int i=get(x,y);i;i-=lowbit(i))
{
int t = map[lowbit(i)];
row[x] -= (1<<t);
col[y] -= (1<<t);
cell[x/3][y/3] -= (1<<t);
str[x*9+y] = t+'1';
if(dfs(cnt-1))
return true;
row[x] += (1<<t);
col[y] += (1<<t);
cell[x/3][y/3] += (1<<t);
str[x*9+y] = '.';
}
return false;
}
int main() {
for(int i=0;i<N;i++)
{
map[1<<i] = i;
}
for(int i=0;i<(1<<N);i++)
{
int sum = 0;
for(int j=i;j;j-=lowbit(j))
{
sum++;
}
ones[i] = sum;
}
while(cin >> str,str[0]!='e')
{
init();
int cnt=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(str[j+i*9]!='.')
{
int cnt = str[j+i*9] - '1';
row[i] -= (1 << cnt);
col[j] -= (1 << cnt);
cell[i/3][j/3] -= (1<<cnt);
}
else
{
cnt++;
}
}
}
dfs(cnt);
cout << str << "
";
}
return 0;
}