字符串 dfs 搜索 剪枝
#include<iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
string str_st,str_en;
string A[7], B[7];
queue<string> que;
queue<int> step;
map<string, int> mp;
int n;
int bfs() {
bool bo = false;
while (que.empty() == 0&&step.front()<10)
{
if (mp[que.front()] == 1)
{
step.pop();
que.pop();
continue;
}
mp[que.front()] = 1;
for (int i = 0; i < n; i++)
{
string str = que.front();
while (true)
{
int place = str.find(A[i]);
if (place == -1)
break;
string str_1 = que.front();
str_1.replace(place, A[i].size(), B[i]);
que.push(str_1);
str[place] = '*';
step.push(step.front() + 1);
if (str_1 == str_en)
{
bo = true;
break;
}
}
if (bo)
break;
}
que.pop();
step.pop();
if (bo)
return step.back();
}
return 0;
}
int main() {
cin >> str_st >> str_en;
que.push(str_st);
step.push(0);
while (cin >> A[n] >> B[n]) n++;
int ans = bfs();
if (ans != 0)
cout << ans << endl;
else
cout << "NO ANSWER!" << endl;
system("pause");
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/22743cc5808157da1ced1df7eea23abf.jpeg#pic_center)