在BFS搜索的过程中,状态的扩展是指数级增长的,为了减少状态数,我们可以从起点和终点双向BFS搜索,且在一个方向的状态数少的情况下多去搜这个方向。在两个方向同时搜到某个状态数结束
注意,不是每个方向一个点一个点的去搜,而是每次搜索一层,这样才保证不会有遗漏的最短路径
AcWing 190. 字串变换
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include<map>
#include <queue>
using namespace std;
string a[6], b[6];
int n;
int extend(queue<string>& q, map<string, int> &da, map<string, int> &db, string a[],string b[])
{
int d = da[q.front()];
while(q.size() && da[q.front()] == d )
{
string t = q.front();
q.pop();
for(int i = 0; i < t.size(); i ++ )
for(int j = 0; j < n; j ++ )
if(t.substr(i, a[j].size()) == a[j])
{
string state = t.substr(0, i) + b[j] + t.substr(i + a[j].size());
if(db.count(state))return da[t] + 1 + db[state];
if(da.count(state))continue;
da[state] = da[t] + 1;
q.push(state);
}
}
return 11;
}
int bfs(string A, string B)
{
if(A == B) return 0;
queue<string>qa, qb;
map<string, int> da, db;
qa.push(A), da[A] = 0;
qb.push(B), db[B] = 0;
while(qa.size() && qb.size())
{
int t;
if(qa.size() <= qb.size())
t = extend(qa,da,db,a,b);
else t = extend(qb,db,da,b,a);
if(t <=10 ) return t;
}
return 11;
}
int main()
{
string A, B;
cin >> A >> B;
while(cin >> a[n] >> b[n]) n ++;
int step = bfs(A,B);
if(step > 10)cout << "NO ANSWER!";
else cout << step;
}