题目:
AC代码:
#include <bits/stdc++.h>
using namespace std;
string s;
unordered_map<string,string> m;
bool check(string x)
{
return x==(string)"12345678x";
}
int main()
{
cin>>s;
queue<string> q;
q.push(s);
m[s]="-1";
while (!q.empty())
{
string now=q.front();
//cout<<"now="<<now<<endl;
string onow=now;
q.pop();
int pos;
for (int i=0;i<9;i++) if (now[i]=='x') pos=i;
if (pos>2)
{
swap(now[pos],now[pos-3]);
if (m.find(now)==m.end())
{
m[now]=onow;
if (check(now)) break;
q.push(now);
}
swap(now[pos],now[pos-3]);
}
if (pos<6)
{
swap(now[pos],now[pos+3]);
if (m.find(now)==m.end())
{
m[now]=onow;
if (check(now)) break;
q.push(now);
}
swap(now[pos],now[pos+3]);
}
if (pos%3!=0)
{
swap(now[pos],now[pos-1]);
if (m.find(now)==m.end())
{
m[now]=onow;
if (check(now)) break;
q.push(now);
}
swap(now[pos],now[pos-1]);
}
if (pos%3!=2)
{
swap(now[pos],now[pos+1]);
if (m.find(now)==m.end())
{
m[now]=onow;
if (check(now)) break;
q.push(now);
}
swap(now[pos],now[pos+1]);
}
}
vector<string> out;
string tar="12345678x";
if(m.find(tar)!=m.end())
{
for (;tar!="-1";tar=m[tar])
{
out.push_back(tar);
}
reverse(out.begin(),out.end());
//cout<<out.size()<<endl;
//for (auto x:out) cout<<x<<endl;
for (int i=0;i<(int)out.size()-1;i++)
{
int temp1,temp2;
for(int j=0;j<(int)out[i].size();j++)
{
if(out[i][j]=='x') temp1=j;
}
for(int j=0;j<(int)out[i+1].size();j++)
{
if(out[i+1][j]=='x') temp2=j;
}
if(temp2-temp1==3) cout<<"d";
if(temp2-temp1==-3) cout<<"u";
if(temp2-temp1==1) cout<<"r";
if(temp2-temp1==-1) cout<<"l";
}
cout<<endl;
}
else cout<<"unsolvable"<<endl;
return 0;
}