字串变换(双向BFS)

双向BFS

190. 字串变换

![在这里插入图片描述]( https://img-blog.csdnimg.cn/75b5630369c24839874b21f255b939fc.png?x-oss-process=image/watermark ,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAUGFuc2XCtw==,size_20,color_FFFFFF,t_70,g_se,x_16)
样例输入:

abcd xyz
abc xu
ud y
y yz

样例输出:

3

代码模板:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>

using namespace std;

const int N = 6;

int n;
string A, B;
string a[N], b[N];

int extend(queue<string>& q, unordered_map<string, int>&da, unordered_map<string, int>& db, 
    string a[N], string b[N])
{
        auto t = q.front();
        q.pop();

        for (int i = 0; i < n; i ++ ) //枚举规则
            for (int j = 0; j < t.size(); j ++ ) //枚举字符串的位置
                if (t.substr(j, a[i].size()) == a[i])
                {
                    string r = t.substr(0, j) + b[i] + t.substr(j + a[i].size());//连接
                    if (db.count(r)) return da[t] + db[r] + 1;  //会师
                    if (da.count(r)) continue;  //重复continue
                    da[r] = da[t] + 1;
                    q.push(r);
                }

    return 11;
}

int bfs()
{
    if (A == B) return 0;
    queue<string> qa, qb;
    unordered_map<string, int> da, db;

    qa.push(A), qb.push(B);
    da[A] = db[B] = 0;

    int step = 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()
{
    cin >> A >> B;
    while (cin >> a[n] >> b[n]) n ++ ;

    int t = bfs();
    if (t > 10) puts("NO ANSWER!");
    else cout << t << endl;

    return 0;
}

 

posted @ 2022-03-22 14:45  panse·  阅读(37)  评论(0)    收藏  举报