标签:ssr long ios char printf code div oal void
八数码-->BFS+set
1 #include<iostream> 2 #include<cstdlib> 3 #include<cstdio> 4 #include<cstring> 5 #include<set> 6 using namespace std; 7 struct aaa{ 8 int map[4][4]; 9 int dep,x,y; 10 }que[370000]; 11 set<int> ssr; 12 int head=0,tail=1; 13 int dx[5]={0,1,-1,0,0}; 14 int dy[5]={0,0,0, 1,-1}; 15 int start[4][4]; 16 int goal[4][4]={{0,0,0,0},{0,1,2,3},{0,8,0,4},{0,7,6,5}}; 17 int temp[4][4]; 18 char putt[15]; 19 long long ans; 20 /*int judge() 21 { 22 int i,j,k; 23 for(i=1;i<=tail;i++) 24 { 25 bool p=1; 26 for(j=1;j<=3;j++) 27 for(k=1;k<=3;k++) 28 if(que[i].map[j][k]!=temp[j][k]) 29 p=0; 30 if(p==1) 31 return 0; 32 } 33 return 1; 34 }*/ 35 36 int judge() 37 { 38 long long num=0; 39 int l,k; 40 for(l=1;l<=3;l++) 41 for(k=1;k<=3;k++) 42 num=num*10+temp[l][k]; 43 pair<set<int>::iterator,bool>f=ssr.insert(num); 44 return f.second; 45 } 46 int win(){ 47 int i,j; 48 for(i=1;i<=3;i++) 49 for(j=1;j<=3;j++) 50 if(temp[i][j]!=goal[i][j]) 51 return 0; 52 return 1; 53 } 54 void bfs() 55 { 56 int i,j; 57 memcpy(temp,start,sizeof (start)); 58 if(win()) 59 return; 60 memcpy(que[tail].map,start,sizeof (start)); 61 for(i=1;i<=3;i++) 62 for(j=1;j<=3;j++) 63 { 64 if(start[i][j]==0) 65 { 66 que[tail].x=i;que[tail].y=j; 67 break; 68 } 69 } 70 71 72 while(head<tail) 73 { 74 head++; 75 for(i=1;i<=4;i++) 76 { 77 int newx=que[head].x+dx[i]; 78 int newy=que[head].y+dy[i]; 79 if(newx>=1&&newy>=1&&newx<=3&&newy<=3) 80 { 81 memcpy(temp,que[head].map,sizeof(temp));// 82 swap(temp[newx][newy],temp[que[head].x][que[head].y]); 83 if(judge()) 84 { 85 tail++; 86 que[tail].x=newx; 87 que[tail].y=newy; 88 memcpy(que[tail].map,temp,sizeof(temp)); 89 que[tail].dep=que[head].dep+1; 90 if(win()) 91 { 92 ans=que[tail].dep; 93 return; 94 } 95 } 96 } 97 } 98 } 99 } 100 int main() 101 { 102 int i,j; 103 scanf("%s",putt); 104 for(i=1;i<=9;i++) 105 start[(i-1)/3+1][(i-1)%3+1]=putt[i-1]-48; 106 bfs(); 107 printf("%d",ans); 108 return 0; 109 }
标签:ssr long ios char printf code div oal void
原文地址:https://www.cnblogs.com/oybdooo-ozai/p/10389394.html