骑士精神

第一次‘写’IDA*,要记住这种写法,以后用到的时候就要敢写

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cmath>
 6 using namespace std;
 7 const int maxn=7;
 8 int t,stx,sty;
 9 int mp[maxn][maxn];
10 int mu[7][7]={{0,0,0,0,0,0},
11               {0,1,1,1,1,1},
12               {0,0,1,1,1,1},
13               {0,0,0,2,1,1},
14               {0,0,0,0,0,1},
15               {0,0,0,0,0,0},
16              };
17 int dx[17]={0,2,1,-2,-1, 2, 1,-2,-1};
18 int dy[17]={0,1,2, 1, 2,-1,-2,-1,-2};
19 bool flag;
20 int pan(){
21   int ret=0;
22   for(int i=1;i<=5;i++)
23     for(int j=1;j<=5;j++)
24       if(mp[i][j]!=mu[i][j]) ret++; 
25   return ret;
26 }
27 bool check(int x,int y){
28   if(x<1||x>5||y<1||y>5) return true;
29   return false;
30 }
31 void dfs(int stp,int x,int y,int req){
32   if(stp==req){
33     if(!pan()) flag=true;
34     return; 
35   }
36   for(int i=1;i<=8;i++){
37     int xx=x+dx[i];int yy=y+dy[i];
38     if(check(xx,yy)) continue;
39     swap(mp[xx][yy],mp[x][y]);
40     int tmp=pan();
41     if(tmp+stp<=req) dfs(stp+1,xx,yy,req);
42     swap(mp[xx][yy],mp[x][y]);
43   }
44 }
45 int main(){
46   scanf("%d",&t);
47   while(t--){
48       flag=false;
49     for(int i=1;i<=5;i++)
50       for(int j=1;j<=5;j++){
51         char t;cin>>t;
52         if(t=='*'){mp[i][j]=2;stx=i;sty=j;}
53         else mp[i][j]=t-'0';
54       }
55     if(pan()==0) cout<<0<<endl;
56     else{
57       for(int i=1;i<=15;i++){
58         dfs(0,stx,sty,i);
59         if(flag){cout<<i<<endl;break;}
60       }
61       if(!flag) cout<<-1<<endl;
62     } 
63   }
64 } 

 

原文地址:https://www.cnblogs.com/lcan/p/9888828.html