https://www.luogu.org/problem/show?pid=1379
突然发现八数码难题挺有意思的
貌似关于这一个问题就能延伸出好多种算法
挖个坑,慢慢填2333
BFS+map
第一发
裸的BFS
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 #include<map> 6 #include<cstdlib> 7 using namespace std; 8 const int n=3; 9 inline void read(int &n) 10 { 11 char c=getchar();bool flag=0;n=0; 12 while(c<'0'||c>'9') c=='-'?flag=1,c=getchar():c=getchar(); 13 while(c>='0'&&c<='9') n=n*10+c-48,c=getchar();flag==1?n=-n:n=n; 14 } 15 map<string,bool>vis; 16 struct node 17 { 18 int a[4][4]; 19 int step; 20 }cur,nxt,ed; 21 inline void debug(node p) 22 { 23 printf("***********\n"); 24 for(int i=1;i<=n;i++) 25 { 26 for(int j=1;j<=n;j++) 27 printf("%d ",p.a[i][j]); 28 putchar('\n'); 29 } 30 printf("***********\n"); 31 } 32 int xx[5]={-1,+1,0,0}; 33 int yy[5]={0,0,-1,+1}; 34 bool pd(node p) 35 { 36 string s; 37 for(int i=1;i<=n;i++) 38 for(int j=1;j<=n;j++) 39 s=s+(char)(p.a[i][j]-48); 40 if(vis[s]==0){ vis[s]=1;return 0; } 41 else return 1; 42 } 43 bool findans(node p) 44 { 45 for(int i=1;i<=n;i++) 46 for(int j=1;j<=n;j++) 47 if(p.a[i][j]!=ed.a[i][j]) return 0; 48 return 1; 49 } 50 inline void BFS() 51 { 52 queue<node>q; 53 q.push(cur); 54 while(q.size()!=0) 55 { 56 node p=q.front(); 57 //debug(p); 58 if(findans(p)==1) 59 { 60 printf("%d",p.step); 61 exit(0); 62 } 63 q.pop(); 64 bool flag=0; 65 for(int i=1;i<=n;i++) 66 { 67 for(int j=1;j<=n;j++) 68 { 69 if(p.a[i][j]==0) 70 { 71 for(int k=0;k<4;k++) 72 { 73 int wx=i+xx[k]; 74 int wy=j+yy[k]; 75 if(wx>=1&&wx<=n&&wy>=1&&wy<=n) 76 { 77 node nxt=p; 78 swap(nxt.a[i][j],nxt.a[wx][wy]); 79 nxt.step=p.step+1; 80 if( pd(nxt) == 0 ) 81 q.push(nxt); 82 } 83 } 84 flag=1;break; 85 } 86 } 87 if(flag==1) break; 88 } 89 90 } 91 } 92 int main() 93 { 94 ed.a[1][1]=1;ed.a[1][2]=2;ed.a[1][3]=3;ed.a[2][1]=8;ed.a[2][2]=0;ed.a[2][3]=4;ed.a[3][1]=7;ed.a[3][2]=6;ed.a[3][3]=5; 95 for(int i=1;i<=n;i++) 96 for(int j=1;j<=n;j++) 97 { char c=getchar();cur.a[i][j]=c-48; } 98 cur.step=0; 99 BFS(); 100 return 0; 101 }