我把这个当做IDA*的模板题的说,说说我个人对IDA*的理解
IDA*是一个DFS,和A*一样,它也有一个乐观的估价函数。这里这个估价函数是用来限制状态的扩展的,如果当前代价加上乐观的估计都无法在规定层数内出解,我们就不向更深搜索了。这里取位置有差异的骑士个数作为估价函数即可,注意是骑士个数,因为在最后一步的时候我们有两个差异位置,然而实际上我们只要让一个骑士跳一步就可以完成了。这里我偷懒直接在差异位置上减掉了$1$......

1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 const int goal[6][6]= 6 { 7 {0,0,0,0,0,0}, 8 {0,1,1,1,1,1}, 9 {0,0,1,1,1,1}, 10 {0,0,0,2,1,1}, 11 {0,0,0,0,0,1}, 12 {0,0,0,0,0,0} 13 }; 14 const int mov[8][2]= 15 {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}}; 16 int mapp[6][6]; char rd[6]; 17 int T,sx,sy,lim,able; 18 int dif() 19 { 20 int ret=0; 21 for(int i=1;i<=5;i++) 22 for(int j=1;j<=5;j++) 23 ret+=(mapp[i][j]!=goal[i][j]); 24 return ret; 25 } 26 void IDAstar(int x,int y,int stp) 27 { 28 if(stp>lim) 29 { 30 if(!dif()) able=true; 31 return ; 32 } 33 for(int i=0;i<8&&!able;i++) 34 { 35 int tx=x+mov[i][0],ty=y+mov[i][1]; 36 if(tx>=1&&tx<=5&&ty>=1&&ty<=5) 37 { 38 swap(mapp[x][y],mapp[tx][ty]); 39 if(dif()+stp-1<=lim) IDAstar(tx,ty,stp+1); 40 swap(mapp[x][y],mapp[tx][ty]); 41 } 42 } 43 } 44 int main () 45 { 46 scanf("%d",&T); 47 while(T--) 48 { 49 for(int i=1;i<=5;i++) 50 { 51 scanf("%s",rd+1); 52 for(int j=1;j<=5;j++) 53 if(rd[j]=='*') mapp[i][j]=2,sx=i,sy=j; 54 else mapp[i][j]=(rd[j]-'0'); 55 } 56 bool found=false; 57 if(!dif()) {puts("0"); continue;} 58 for(int i=1;i<=15;i++) 59 { 60 lim=i,able=false,IDAstar(sx,sy,1); 61 if(able) {printf("%d ",i); found=true; break;} 62 } 63 if(!found) printf("-1 "); 64 } 65 return 0; 66 }