题目链接:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1085
考虑到深度不超过15,IDA*搜索可做。
估价函数h()=当前不在目标位置的棋子个数。
然后其他细节就和普通的迭代加深一样了。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
int xx[]={1,1,-1,-1,2,2,-2,-2};
int yy[]={2,-2,2,-2,1,-1,1,-1};
char map[6][6];
char goal[6][6]={
{0,0,0,0,0,0},
{0,'1','1','1','1','1'},
{0,'0','1','1','1','1'},
{0,'0','0','*','1','1'},
{0,'0','0','0','0','1'},
{0,'0','0','0','0','0'}
}; //目标棋盘
bool inMap(int x,int y)
{
if(x<1||x>5||y<1||y>5) return false;
return true;
}
int h() //估价函数
{
int ans=0;
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
ans+=(goal[i][j]!=map[i][j]);
return ans;
}
bool IDAstar(int step,int maxdeep)
{
if(step>maxdeep) return false;
int predict=h(),bx,by; //空格坐标为(bx,by)
if(!predict) return true; //达到目标状态
if(predict-1+step>maxdeep) return false; //h()函数剪枝
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
if(map[i][j]=='*')
bx=i,by=j;
for(int dir=0;dir<8;dir++)
{
int tx=bx+xx[dir],ty=by+yy[dir];
if(!inMap(tx,ty)) continue;
swap(map[bx][by],map[tx][ty]);
if(IDAstar(step+1,maxdeep)) return true;
swap(map[bx][by],map[tx][ty]);
}
return false;
}
int main()
{
int T,maxdeep;
scanf("%d",&T);
while(T--)
{
for(int i=1;i<=5;i++)
scanf("%s",map[i]+1);
for(maxdeep=0;maxdeep<=15;maxdeep++)
{
if(IDAstar(0,maxdeep))
{
printf("%d\n",maxdeep);
break;
}
}
if(maxdeep>15) puts("-1");
}
return 0;
}