一道很典型的搜索题
就是有个很神奇的方法可以减少搜索时间
// 就是从含有0最少的一行开始搜(膜拜某谷大佬) //
其实自己做数独的时候
应该也会有小伙伴这么做(方便)
上代码
#include<bits/stdc++.h>
using namespace std;
const int MAX=10;
struct node{
int x;
int cnt;
}k[MAX];
int head[MAX];//记录下一个要搜索的x行
int score[10][10]={
{0,0,0,0,0,0,0,0,0,0},
{0,6,6,6,6,6,6,6,6,6},
{0,6,7,7,7,7,7,7,7,6},
{0,6,7,8,8,8,8,8,7,6},
{0,6,7,8,9,9,9,8,7,6},
{0,6,7,8,9,10,9,8,7,6},
{0,6,7,8,9,9,9,8,7,6},
{0,6,7,8,8,8,8,8,7,6},
{0,6,7,7,7,7,7,7,7,6},
{0,6,6,6,6,6,6,6,6,6}
};
long long ans;
int a[MAX][MAX];
long long max1=0;
int len_x[MAX][MAX],len_y[MAX][MAX];//判断横的和竖的是否被占了
int mark[MAX][MAX];//判断小九宫格是否被占了
int mark_len[MAX][MAX]={
{0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,2,2,2,3,3,3},
{0,1,1,1,2,2,2,3,3,3},
{0,1,1,1,2,2,2,3,3,3},
{0,4,4,4,5,5,5,6,6,6},
{0,4,4,4,5,5,5,6,6,6},
{0,4,4,4,5,5,5,6,6,6},
{0,7,7,7,8,8,8,9,9,9},
{0,7,7,7,8,8,8,9,9,9},
{0,7,7,7,8,8,8,9,9,9}
};//(蒟蒻)存小九宫格的方法
int tot=0;
int o;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')
w=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
s=s*10+ch-'0';
ch=getchar();
}
return s*w;
}
bool cmp(node x,node y)
{
return x.cnt<y.cnt;
}
int dfs()
{
/*cout<<endl;
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}*/
for(int i=k[1].x;head[i]!=-1;i=head[i])
{
for(int j=1;j<=9;j++)
{
if(a[i][j]==0)
{
bool tmp = false;
for(int k=1;k<=9;k++)
{
if(len_x[i][k]==0&&len_y[j][k]==0&&mark[mark_len[i][j]][k]==0)
{
len_x[i][k]=1;
len_y[j][k]=1;
mark[mark_len[i][j]][k]=1;
a[i][j]=k;
if(dfs()>0) tmp = true;
a[i][j]=0;
len_x[i][k]=0;
len_y[j][k]=0;
mark[mark_len[i][j]][k]=0;
}
}
if(!tmp) return 0;//如果这个位置放放不了数return掉
//如果不判断会有很严重的后果(死循环,无限种情况)
}
}
}
for(int i=1;i<=9;i++)
for(int j=1;j<=9;j++)
if(a[i][j]==0)
return 0;
ans=0;
for(int i=1;i<=9;i++)
for(int j=1;j<=9;j++)
ans+=score[i][j]*a[i][j];
max1=max(max1,ans);
return ans;
}
int main()
{
for(int i=1;i<=9;i++)
for(int j=1;j<=9;j++)
{
a[i][j]=read();
if(a[i][j]!=0)
{
len_x[i][a[i][j]]=1;
len_y[j][a[i][j]]=1;
mark[mark_len[i][j]][a[i][j]]=1;
}
else
{
k[i].cnt++;
k[i].x=i;
tot++;
}
}
sort(k+1,k+10,cmp);
for(int i=1;i<=9;i++)
head[k[i].x]=k[i+1].x;
head[k[10].x]=-1;
/*for(int i=1;i<=9;i++)
cout<<k[i].x<<" ";
cout << endl;*/
dfs();
if(max1==0)
cout<<-1<<endl;
else
cout<<max1<<endl;
return 0;
}