我的思路是将字符串存到一个队列里,然后i循环队列里的字符串,j循环找到这个字符串能用的规则,将用了规则的新字符串存到队列中,重复执行以上操作直到操作了十次或有一个新字符串变成了目标字符串。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int main(){
string A,B;
cin>>A>>B;
vector<pair<string,string> >rules;
string a,b;
while(cin>>a>>b)rules.emplace_back(a,b);
queue<string>q;
unordered_set<string>visited;
q.push(A),visited.insert(A);
int step=0;
while(!q.empty()&&step<=10){
int size=q.size();
for(int i=0;i<size;i++){
string current=q.front();
q.pop();
if(current==B){
cout<<step;
return 0;
}
for(const auto&rule:rules){
const string& from=rule.first;
const string& to=rule.second;
size_t pos=0;
while((pos=current.find(from,pos))!=string::npos){
string next=current;
next.replace(pos,from.length(),to);
if(visited.find(next) == visited.end())
visited.insert(next),q.push(next);
pos++;
}
}
}
step++;
}
cout<<"NO ANSWER!";
return 0;
}