迭代加深搜索。

剪枝:当满足以下任意一个条件退出:

    1.当前已搜到答案时(ans!=-1||sum==0)

    2.剩余步数+1<当前局面与目标局面不同的格子数sum 时(因为n步最多改变n+1个格子)

    3.当前步数>当前规定最大步数时

 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 const int n=5,m=8,maxstep=15;
 5 int a[6][6],b[6][6]={{0,0,0,0,0,0},
 6     {0,1,1,1,1,1},{0,0,1,1,1,1},
 7     {0,0,0,-1,1,1},{0,0,0,0,0,1},
 8     {0,0,0,0,0,0}};
 9 int    fh[9]={0,-2,-1,1,2,2,1,-1,-2},
10     fl[9]={0,1,2,2,1,-1,-2,-2,-1};
11 int ex,ey,ans,step;
12 void swap(int,int,int,int),work(),
13   dfs(int,int,int),read();
14 int change(char),check(),pd(int,int);
15 int main(){
16     int t;
17     scanf("%d",&t);
18     for (int i=1;i<=t;i++) work();
19     return 0;
20 }
21 void work(){
22     ans=-1;read();
23     for (step=0;step<=maxstep;step++){
24         dfs(0,ex,ey);
25         if (ans!=-1) break;
26     }
27     printf("%d\n",ans);
28     return;
29 } 
30 void read(){
31     char c[7];
32     for (int i=1;i<=n;i++){
33         scanf("%s",&c);
34         for (int j=0;j<n;j++){
35             a[i][j+1]=change(c[j]);
36             if (a[i][j+1]==-1){
37                 ex=i;ey=j+1;
38             }
39         } 
40     }
41     return;
42 }
43 void dfs(int deep,int p,int q){
44     int x,y,sum;
45     if (ans!=-1) return;
46     sum=check();
47     if (deep==step){
48         if (!sum) ans=deep;return;
49     }
50     else if (step-deep+1<sum) return;
51     if (deep>step) return; 
52     for (int i=1;i<=m;i++){
53         x=p+fh[i];y=q+fl[i];
54         if (pd(x,y)){
55             swap(x,y,p,q);
56             dfs(deep+1,x,y);
57             swap(x,y,p,q);
58         } 
59     }
60 }
61 int change(char c){
62     if (c=='1') return 1;
63     if (c=='0') return 0;
64     if (c=='*') return -1;
65 }
66 int check(){
67     int sum=0;
68     for (int i=1;i<=n;i++)
69         for (int j=1;j<=n;j++)
70             if (a[i][j]!=b[i][j]) sum++;
71     return sum;
72 }
73 int pd(int p,int q){
74     if (p>=1&&q>=1&&p<=n&&q<=n) return 1;
75     return 0;
76 }
77 void swap(int x,int y,int p,int q){
78     int tmp;
79     tmp=a[x][y];a[x][y]=a[p][q];a[p][q]=tmp;
80     return;
81 }
STD

 

posted on 2016-09-02 16:21  Absolutezero  阅读(111)  评论(0编辑  收藏  举报