估值函数为:当前棋盘与目标棋盘不同的位置数量-1
易知一个棋盘最少需要这么多的步数才能达成目标棋盘
若当前步数+估值函数大于最大深度 则剪枝
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*f;
}
char mp[5][6],tar[5][6]={"11111","01111","00*11","00001","00000"};
int dx[]={1,1,-1,-1,2,2,-2,-2},dy[]={2,-2,2,-2,1,-1,1,-1},mx_dep;
bool flag;
inline int eval(){
int res=0;
for(int i=0;i<5;++i)
for(int j=0;j<5;++j) res+=(mp[i][j]!=tar[i][j]);
return res-1;
}
void dfs(int dep,int x,int y){
int tmp=eval();
if(tmp==-1){flag=1;return;}
if(dep+tmp>mx_dep) return;
for(int k=0;k<8;++k){
int xx=x+dx[k],yy=y+dy[k];
if(xx<0||xx>4||yy<0||yy>4) continue;
swap(mp[x][y],mp[xx][yy]);dfs(dep+1,xx,yy);
swap(mp[x][y],mp[xx][yy]);if(flag) return;
}
}
int main(){
// freopen("a.in","r",stdin);
int tst=read();
while(tst--){
int x,y;flag=0;
for(int i=0;i<5;++i){
scanf("%s",mp[i]);
for(int j=0;j<5;++j) if(mp[i][j]=='*') x=i,y=j;
}for(mx_dep=0;mx_dep<=15;++mx_dep){
dfs(0,x,y);if(flag) break;
}if(mx_dep==16) puts("-1");
else printf("%d\n",mx_dep);
}return 0;
}