八数码问题--bfs

 1 #include<iostream>
 2 #include<cstring>
 3 #define max 1000000
 4 using namespace std;
 5 const int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
 6 string origion;
 7 string goal;
 8 string state[max];
 9 int vis[370000];
10 
11 bool encode(string str){  //康拖展开 编码
12     int x=1,sum=0,n=8;
13     for(int i=1;i<9;i++){
14         x=i*x;
15     }
16     for( int i=0 ; i < str.length() ; i++){
17         if( str[i]<='9' && str[i]>='0' ){
18             int cnt=0;
19             for(int j=i+1 ; j<str.length() ; j++){
20                 if(str[j]!=' '&& str[j] < str[i]){
21                     cnt++;
22                 }
23             }
24             sum+=cnt*x;        
25             if(x!=1)
26                 x=x/n;
27                 n--;        
28         }
29     }
30     if(vis[sum]){
31         vis[sum]=0;
32         return true;
33     }
34     return false;
35 }
36 int bfs(){
37     state[0]=origion;
38     encode(origion);
39     int front=0,rear=1;
40     int floor=0,amt=1;
41     int temp=0;
42     
43     while(front!=rear){
44         string str1=state[front],str2=str1;
45         front=(front+1)%max;
46 
47         if(amt==0){
48             amt=temp;
49             temp=0;
50             floor++;
51         }
52         if(str1==goal){
53             return floor;
54         }
55         int pos=0,i,j;
56         while(pos<str1.length()){
57             if(str1[pos]=='0') break;
58             pos++;
59         }
60         i=pos/6;
61         j=(pos/2)%3;
62         
63         for(int k=0;k<4;k++){
64             str1=str2;
65             int x=i+dir[k][0];
66             int y=j+dir[k][1];
67             
68             if(x>=0&&x<3&&y>=0&&y<3){
69                 char t=str1[pos];
70                 str1[pos]=str1[x*6+y*2];
71                 str1[x*6+y*2]=t;
72                 
73                 if(encode(str1)){
74                     if( (rear+1)%max == front)
75                         return -1;
76                     state[rear]=str1;
77                     rear = (rear+1)%max;
78                     temp++;
79                 }
80                 
81             }
82         }
83         amt--;
84     }
85     return 0;
86 }
87 int main(){
88     while( getline(cin,origion) && getline(cin,goal)){
89         memset(vis,-1,sizeof(vis));
90         cout<<bfs()<<endl;
91     }    
92 }
93 /*
94 2 6 4 1 3 7 0 5 8
95 8 1 5 7 3 6 4 0 2
96 */

 

posted @ 2018-02-14 20:05  bear_ge  阅读(229)  评论(0编辑  收藏  举报