题解:可以预处理出已经填数字比较密集的区域开始搜索来减少后续决策数
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int n=9;
int s,tot,ans;
int a[10][10];
struct data{
bool h,l,k;
}f[10][10];
int fen[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}};
int search(int i,int j)
{
if(i<=3)
{
if(j<=3) return 1;
if(j>3&&j<=6) return 2;
if(j>6&&j<=9) return 3;
}
if(i>3&&i<=6)
{
if(j<=3) return 4;
if(j>3&&j<=6) return 5;
if(j>6&&j<=9) return 6;
}
if(i>6&&i<=9)
{
if(j<=3) return 7;
if(j>3&&j<=6) return 8;
if(j>6&&j<=9) return 9;
}
}
void dfs(int x,int y)
{
if(y<1)
{
y=9;
x--;
}
if(x==0)//若搜索到x=1,y=0时,更新最大值,此时x-1=0
ans=tot>ans?tot:ans;
if(a[x][y]==0)
{
for(int i=1;i<=9;i++)
{
if(!f[x][i].h&&!f[y][i].l&&!f[search(x,y)][i].k)
{
a[x][y]=i;
tot+=fen[x][y]*i;
f[x][i].h=f[y][i].l=f[search(x,y)][i].k=1;
dfs(x,y-1);
a[x][y]=0;
tot-=fen[x][y]*i;
f[x][i].h=f[y][i].l=f[search(x,y)][i].k=0;
}
}
}
else dfs(x,y-1);
}
int main()
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j])
{
f[i][a[i][j]].h=1;
f[j][a[i][j]].l=1;
f[search(i,j)][a[i][j]].k=1;
ans+=a[i][j]*fen[i][j];
}
}
tot=ans;
dfs(n,n);
if(ans==tot) cout<<"-1"<<endl;
else cout<<ans<<endl;
return 0;
}
以后再写