一开始打了个爆搜,然后心里不稳网上一看,原来果然是A*
这段代码是迭代加深搜加A*的
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int dx[]={-2,-1,1,2,2,1,-1,-2};
const int dy[]={-1,-2,-2,-1,1,2,2,1};
char s[9];
int T,ok,x,y,k,a[5][5];
int goal[5][5]={{1,1,1,1,1},
{0,1,1,1,1},
{0,0,2,1,1},
{0,0,0,0,1},
{0,0,0,0,0}};
bool okk(int dep){
int cnt=0;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(a[i][j]!=goal[i][j]){
cnt++;
if(cnt+dep>k){
return false;
}
}
}
}
return true;
}
void dfs(int dep,int x,int y){
if(dep==k&&!memcmp(a,goal,sizeof a)){
ok=1;
return;
}
for(int i=0;i<8;i++){
if(!ok&&dep<k){
int xx=x+dx[i],yy=y+dy[i];
if(xx>=0&&xx<5&&yy>=0&&yy<5){
swap(a[x][y],a[xx][yy]);
if(okk(dep)){
dfs(dep+1,xx,yy);
}
swap(a[x][y],a[xx][yy]);
}
}
}
}
int main(){
cin>>T;
while(T--){
for(int i=0;i<5;i++){
scanf("%s",s);
for(int j=0;j<5;j++){
if(s[j]=='*'){
x=i,y=j,a[i][j]=2;
}else{
a[i][j]=s[j]-'0';
}
}
}
ok=0;
for(k=0;k<=15;k++){
dfs(0,x,y);
if(ok){
printf("%d\n", k);break;
}
}
if(!ok){
cout<<-1<<endl;
}
}
return 0;
}
/*
2
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
*/
/*
7
-1
*/