https://www.acwing.com/problem/content/description/192/
普通的搜索
双向广搜
#include<bits/stdc++.h>
using namespace std;
const int N=10;
string a[N],b[N],A,B;
int n;
int change(queue<string> &q,unordered_map<string,int>&hush1,unordered_map<string,int>&hush2,string a[],string b[])
{
int step=hush1[q.front()];
while(q.size()&&hush1[q.front()]==step)
{
string u=q.front(); q.pop();
for(int i=0;i<n;i++)
{
for(int j=0;j<u.size();j++)
{
if(u.substr(j,a[i].size())==a[i])
{
string temp=u.substr(0,j)+b[i]+u.substr(j+a[i].size());
if(hush2.count(temp)) return hush1[u]+1+hush2[temp];//说明碰头了
if(hush1.count(temp)) continue;
hush1[temp]=hush1[u]+1;
q.push(temp);
}
}
}
}
return 11;
}
int bfs()
{
if(A==B) return 0;
queue<string>qa,qb;
unordered_map<string,int>hush1,hush2;
qa.push(A),qb.push(B);
hush1[A]=0,hush2[B]=0;
int step=0;
while(qa.size()&&qb.size())
{
int t=0;
if(qa.size()<qb.size()) t=change(qa,hush1,hush2,a,b);//让较少状态的队列扩展
else t=change(qb,hush2,hush1,b,a);
if(t<=10) return t;
if(++step==10) return -1;
}
return -1;
}
int main(void)
{
cin>>A>>B;
while(cin>>a[n]>>b[n]) n++;
int t=bfs();
if(t==-1) puts("NO ANSWER!");
else cout<<t<<endl;
return 0;
}