Title Link: http://www.lydsy.com:808/JudgeOnline/problem.php?id=1085
Consider the depth of not more than 15,ida* search can do.
Valuation function h () = The number of pieces that are not currently in the target position.
Then the rest of the details are just as deep as normal iterations.
#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 '}; Target checkerboard bool Inmap (int x,int y) {if (x<1| | x>5| | y<1| | Y>5) return false; return true;} int h ()//valuation function {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; The space coordinates are (bx,by) if (!predict) return true; Reach the target State if (Predict-1+step>maxdeep) return false; The h () function pruning 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;}
[Bzoj 1085] [Scoi 2005] Knight Spirit (ida* Search)