标签:
裸A*,ans从1到15循环来限制搜索深度。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int d,s[6][6],ans; 6 char c; 7 bool flag; 8 int ma[6][6]={{0,0,0,0,0,0}, 9 {0,1,1,1,1,1}, 10 {0,0,1,1,1,1}, 11 {0,0,0,2,1,1}, 12 {0,0,0,0,0,1}, 13 {0,0,0,0,0,0}},dx[8]={1,2,2,1,-1,-2,-2,-1},dy[8]={2,1,-1,-2,-2,-1,1,2}; 14 void swap(int &a,int &b){int c=a;a=b;b=c;} 15 bool check() 16 { 17 int i,j; 18 for (i=1;i<=5;++i)for (j=1;j<=5;++j)if (s[i][j]!=ma[i][j]) return 0; 19 return 1; 20 } 21 bool f(int g) 22 { 23 int h=0,i,j; 24 for (i=1;i<=5;++i)for (j=1;j<=5;++j)if (s[i][j]!=ma[i][j]) 25 {h++; if (g+h>ans) return 0;} 26 return 1; 27 } 28 void dfs(int x,int y,int g) 29 { 30 if (g==ans) 31 { 32 if (check()) flag=1; 33 return; 34 } 35 if (flag) return; 36 int i,nowx,nowy; 37 for (i=0;i<8;++i) 38 { 39 nowx=x+dx[i];nowy=y+dy[i]; 40 if ((nowx<1)||(nowy<1)||(nowx>5)||(nowy>5)) continue; 41 swap(s[x][y],s[nowx][nowy]); 42 if (f(g)) dfs (nowx,nowy,g+1); 43 swap(s[nowx][nowy],s[x][y]); 44 } 45 } 46 int main() 47 { 48 int i,j,t,x,y; 49 scanf("%d\n",&t); 50 while (t>0){t--; 51 for (i=1;i<=5;++i) 52 { 53 for (j=1;j<=5;++j) 54 { 55 c=getchar(); 56 if (c==‘*‘) s[i][j]=2,x=i,y=j; 57 else s[i][j]=int(c-‘0‘); 58 } 59 scanf("\n"); 60 } flag=0; 61 for (ans=1;ans<=15;++ans) 62 { 63 dfs(x,y,0); 64 if (flag) break; 65 } 66 if (flag) printf("%d\n",ans); 67 else printf("-1\n"); 68 } 69 return 0; 70 }
标签:
原文地址:http://www.cnblogs.com/abclzr/p/5042991.html