Dfs!Dfs!Dfs
裸Dfs。
大牛楼天城发明了A*算法,要加上这个才会不超时
bool star(int k){
int s=0;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
if(a[i][j]!=ed[i][j]){
s++;if(s+k>ans)return false;
}
}
}
return true;
}
这个就是A*啦,就是剪枝啦。
提交传送门
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
int a[6][6]={
{0,0,0,0,0,0},
{0,1,1,1,1,1},
{0,0,1,1,1,1},
{0,0,0,2,1,1},
{0,0,0,0,0,1},
{0,0,0,0,0,0}
};
int dx[9]={0,2,2,1,-1,-2,-2,-1,1};
int dy[9]={0,-1,1,2,2,1,-1,-2,-2};
char s[110];
int ed[6][6],xx,yy,n,ans;
bool pd(){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
if(a[i][j]!=ed[i][j])return false;
}
}
return true;
}
bool star(int k){
int s=0;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
if(a[i][j]!=ed[i][j]){
s++;if(s+k>ans)return false;
}
}
}
return true;
}
void dfs(int x,int y,int k){
if(k>ans)return ;
if(pd()==true){
ans=min(ans,k);
}
else{
for(int i=1;i<=8;i++){
int nx=x+dx[i],ny=y+dy[i];
if(nx>=1&&nx<=5&&ny>=1&&ny<=5){
swap(a[x][y],a[nx][ny]);
if(star(k)==true)dfs(nx,ny,k+1);
swap(a[x][y],a[nx][ny]);
}
}
}
}
int main(){
freopen("Knight.in","r",stdin);
freopen("Knight.out","w",stdout);
scanf("%d",&n);
while(n--){
for(int i=1;i<=5;i++){
scanf("%s",s+1);
for(int j=1;j<=5;j++){
if(s[j]=='1')ed[i][j]=1;
else if(s[j]=='*'){
xx=i;yy=j;
ed[i][j]=2;
}
else ed[i][j]=0;
}
}
ans=16;
dfs(3,3,0);
if(ans!=16)printf("%d\n",ans);
else printf("-1\n");
}
}