题目:数独
参考:yxc
题意:就是给你一个九宫格,让你填数,使横行包含1 ~ 9,纵行包含1 ~ 9,每一块包含1 ~ 9 。
思路:本题采用深搜,然后通过用col和row分别记录横行和纵行没有被用过的数,cell来标记没有被用过的数,通过0代表这个数已经被用过了,1代表这个数没有被用过,然后通过剪枝找到某个数可以填数的最小可能,这个最小可能通过row[x] & cell[x/3][y/3] & col[y]来找到。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100;
const int N = 9;
char str[maxn];
int cell[10][10],row[maxn],col[maxn];
int mp[1<<N], ones[1<<N];
int lowbit(int x)
{
return x&(-x);
}
void set_init()
{
for(int i = 0; i < N; i++ )mp[1<<i] = i;
for(int i = 0; i < 1<<N; i++)
{
int cn = 0;
for(int j = i; j; j -= lowbit(j))cn++;
ones[i] = cn;
}
}
void init()
{
for(int i = 0; i < N; i++)row[i] = (1<<N)-1, 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 judge(int x, int y)
{
return row[x] & cell[x/3][y/3] & col[y];
}
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*N+j] == '.')
{
int t = ones[judge(i, j)];
if(minn > t)minn = t, x = i, y = j;
}
}
}
for(int i = judge(x, y); i; i -= lowbit(i))
{
int t = mp[lowbit(i)];
row[x] -= 1<<t;
col[y] -= 1<<t;
cell[x/3][y/3] -= 1<<t;
str[x*N+y] = '1'+ t;
if(dfs(cnt-1))return true;
row[x] += 1<<t;//恢复现场
col[y] += 1<< t;
cell[x/3][y/3] += 1<<t;
str[x*N+y] = '.';
}
return false;
}
int main()
{
set_init();//预处理
while(cin>>str && strcmp(str, "end") != 0)
{
init();//初始化为全1
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';
row[i] -= 1<<t;
col[j] -= 1<<t;
cell[i/3][j/3] -= 1<<t;
}
else cnt++;
}
}
dfs(cnt);
printf("%s\n", str);
}
return 0;
}