Description
On a 5x5 chessboard there are 12 white knights and 12 Black Knights, and there is a vacancy. At any time a knight can follow the Knight's Walk (it can go to and its horizontal axis difference is 1, the ordinate difference is 2 or the horizontal axis difference is 2, the ordinate difference is 1 lattice) moved to the vacancy. Given an initial chessboard, how can it be moved to become the following target board: In order to demonstrate chivalry, they must complete the task with a minimum number of steps.
Input
The first line has a positive integer T (t<=10), which represents a total of n sets of data. Next there is the T-5x5 matrix, 0 for the White Knight, 1 for the Black Knight, * for the empty space. There are no blank lines between the two sets of data.
Output
Output one row for each set of data. If you can reach the target State within 15 steps (including 15 steps), the output steps, otherwise output-1.
Heuristic Search
The current state differs from the target state by N, which means that the target State cannot be reached in the n-2 step.
Limit the depth of Dfs, if judged within the limit steps can not reach the target state is pruning,
Gradually increase the depth limit until the answer is found or the depth reaches 15 still no solution
#include <cstdio>intN;intans[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}};intD,MAXDEP;BOOLfo;intnow[5][5];intx0,y0;intxs[]={1,1,-1,-1,2,2,-2,-2};intys[]={2,-2,2,-2,1,-1,1,-1};CharC;inlineBOOLeq () { for(intI=0;i<5; i++) for(intj=0;j<5; j + +)if(Ans[i][j]!=now[i][j])return 0; return 1;} InlinevoidSwapint*a,int*b) { intt=*A; *a=*b; *b=T;} Inlineintminsteps () {inta=-1; for(intI=0;i<5; i++) for(intj=0;j<5; j + +)if(Ans[i][j]!=now[i][j]) a++; returnA;}voidDfsintDEP) { if(FO)return; if(eq ()) {fo=1; D=DEP; return; } for(intI=0;i<8; i++){ intX1=x0+xs[i],y1=y0+ys[i],x2=x0,y2=y0; if(x1<0|| y1<0|| X1>4|| Y1>4)Continue; Swap (now[x0]+y0,now[x1]+y1); if(Dep+minsteps () <MAXDEP) {x0=x1;y0=X1; DFS (DEP+1); X0=x2;y0=Y2; } swap (now[x0]+y0,now[x1]+y1); }}voidREADC (Char&c) { while(c=GetChar ()) { if(c=='0'|| c=='1'|| c=='*')return; }}intMain () {scanf ("%d",&N); while(n--){ for(intI=0;i<5; i++){ for(intj=0;j<5; j + +) {READC (c); NOW[I][J]=c=='0'?0: c=='1'?1:2; if(c=='*') x0=i,y0=J; }} D=-1; Fo=0; for(maxdep=1; maxdep<= the&&!fo;maxdep++) DFS (0); printf ("%d\n", D); } return 0;}
bzoj1085 Knight Spirit