八数码问题
1 #include<stdio.h> 2 #include<string.h> 3 #include<set> 4 #include<time.h> 5 using namespace std; 6 7 typedef int state[9]; 8 const int max=1000000; 9 state st[max],goal; 10 int dist[max]; 11 const int dx[]={-1,1,0,0}; 12 const int dy[]={0,0,-1,1}; 13 14 struct cmp 15 { 16 bool operator ()(int a,int b)const 17 { 18 return memcmp(&st[a],&st[b],sizeof(st[b]))<0; 19 } 20 }; 21 22 set<int, cmp> vis; 23 24 void in() 25 { 26 vis.clear(); 27 } 28 29 int insert(int s) 30 { 31 if(vis.count(s)) return 0; 32 vis.insert(s); 33 return 1; 34 } 35 36 int bfs() 37 { 38 int front,rear,z,d,newy,newz,newx,x,y; 39 rear=2; 40 front=1; 41 //state s,t; 42 in(); 43 while(front<rear) 44 { 45 state &s=st[front]; 46 if(memcmp(goal,s,sizeof(s))==0) return front; 47 for(z=0;z<9;z++) if(!s[z]) break; 48 x=z/3;y=z%3; 49 for(d=0;d<4;d++) 50 { 51 newx=x+dx[d]; 52 newy=y+dy[d]; 53 newz=newx*3+newy; 54 if(newx>=0&&newx<3&&newy>=0&&newy<3) 55 { 56 state &t=st[rear]; 57 memcpy(&t,&s,sizeof(s)); 58 t[newz]=s[z]; 59 t[z]=s[newz]; 60 dist[rear]=dist[front]+1; 61 if(insert(rear)) rear++; 62 } 63 } 64 front++; 65 } 66 return 0; 67 } 68 69 int main() 70 { 71 int i,ans; 72 for(i=0;i<9;i++) scanf("%d",&st[1][i]); 73 for(i=0;i<9;i++) scanf("%d",&goal[i]); 74 ans=bfs(); 75 if(ans>0) printf("%d\n",dist[ans]); 76 else printf("-1\n"); 77 printf("%d\n",clock()/CLOCKS_PER_SEC); 78 return 0; 79 }