八数码 一

xiaoxiao2021-02-27  158

#include<iostream> #include<map> #include<string> #include<vector> #include<queue> #include<sstream> using namespace std; map<string,int> b; map<string,string>b1; string mb="123456780"; string temp; int loop() { queue<string> ss; b[temp]=0; b1[temp]=""; ss.push(temp); int t=1; int step=b[temp]; while(!b.count(mb)&&!ss.empty()) { step=b[ss.front()]; if(t%4==1) //上 { string s1,f1; char k1; f1=s1=ss.front(); int x1; for(int i=0;i<s1.length();i++) if(s1[i]=='0') x1=i; if(x1-3>=0) { k1=s1[x1-3]; s1[x1-3]=s1[x1]; s1[x1]=k1; if(!b.count(s1)) { b1[s1]=b1[f1]+"u"; b[s1]=step+1; ss.push(s1); } } t++; continue; } if(t%4==2) { string s2,f2; char k2; f2=s2=ss.front(); int x2; for(int i=0;i<s2.length();i++) if(s2[i]=='0') x2=i; if(x2+3<=8) { k2=s2[x2+3]; s2[x2+3]=s2[x2]; s2[x2]=k2; if(!b.count(s2)) { b1[s2]=b1[f2]+"d"; b[s2]=step+1; ss.push(s2); } } t++; continue; } if(t%4==3) { string s3,f3; char k3; f3=s3=ss.front(); int x3; for(int i=0;i<s3.length();i++) if(s3[i]=='0') x3=i; if(x3!=0&&x3!=3&&x3!=6) { k3=s3[x3-1]; s3[x3-1]=s3[x3]; s3[x3]=k3; if(!b.count(s3)) { b1[s3]=b1[f3]+"l"; b[s3]=step+1; ss.push(s3); } } t++; continue; } if(t%4==0) { string s4,f4; char k4; f4=s4=ss.front(); int x4; for(int i=0;i<s4.length();i++) if(s4[i]=='0') x4=i; if(x4!=2&&x4!=5&&x4!=8) { k4=s4[x4+1]; s4[x4+1]=s4[x4]; s4[x4]=k4; if(!b.count(s4)) { b1[s4]=b1[f4]+"r"; b[s4]=step+1; ss.push(s4); } } t++; ss.pop(); } } return ss.empty(); } int main() { string ff; string j1,j2,j3,j4,j5,j6,j7,j8,j9; while(cin>>j1) { cin>>j2>>j3>>j4>>j5>>j6>>j7>>j8>>j9; b1.clear(); b.clear(); temp=""; temp=temp+j1+j2+j3+j4+j5+j6+j7+j8+j9; for(int i=0;i<temp.length();i++) if(temp[i]=='x') temp[i]='0'; loop(); if(b.count(mb)) cout<<b1[mb]<<endl; else cout<<"unsolvable"<<endl; } return 0; }
转载请注明原文地址: https://www.6miu.com/read-15254.html

最新回复(0)