非常基础的搜索题
用位运算可以加速判重的过程
别忘了判断输入的部分是否有重复
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <deque>
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define LL long long
#define Pair pair<int,int>
#define LOWBIT(x) x & (-x)
using namespace std;
const int INF=0x7ffffff;
inline int getk(int x,int y)
{
int dr,dc;
dr=(x+2)/3;dc=(y+2)/3;
return (dr-1)*3+dc;
}
int rused[15],cused[15],kused[15];
vector<Pair> v;
int a[15][15];
bool dfs(int step)
{
if (step==6) return true;
int xx=v[step-1].x,yy=v[step-1].y;
int used=rused[xx]|cused[yy]|kused[getk(xx,yy)];
for (int i=1;i<=9;i++)
{
if (used&(1<<(i-1))) continue;
a[xx][yy]=i;
rused[xx]^=(1<<(i-1));
cused[yy]^=(1<<(i-1));
kused[getk(xx,yy)]^=(1<<(i-1));
if (dfs(step+1)) return true;
a[xx][yy]=0;
rused[xx]^=(1<<(i-1));
cused[yy]^=(1<<(i-1));
kused[getk(xx,yy)]^=(1<<(i-1));
}
return false;
}
int main ()
{
bool ff;
int t,i,j,x;
scanf("%d",&t);
string s;
while (t--)
{
v.clear();
memset(rused,0,sizeof(rused));
memset(cused,0,sizeof(cused));
memset(kused,0,sizeof(kused));
ff=true;
for (i=1;i<=9;i++)
{
cin>>s;
for (j=1;j<=9;j++)
{
a[i][j]=s[j-1]-'0';
//scanf("%d",&a[i][j]);
x=a[i][j];
if (x!=0)
{
if (rused[i]&(1<<(x-1)))
{
ff=false;
break;
}
rused[i]|=(1<<(x-1));
if (cused[j]&(1<<(x-1)))
{
ff=false;
break;
}
cused[j]|=(1<<(x-1));
if (kused[getk(i,j)]&(1<<(x-1)))
{
ff=false;
break;
}
kused[getk(i,j)]|=(1<<(x-1));
}
else
v.pb(mp(i,j));
}
//if (!ff) break;
}
if (!ff)
{
printf("Could not complete this grid.\n\n");
continue;
}
if (dfs(1))
{
for (i=1;i<=9;i++)
{
for (j=1;j<=9;j++)
printf("%d",a[i][j]);
printf("\n");
}
printf("\n");
}
else
printf("Could not complete this grid.\n\n");
}
}