190. 字串变换【双向广搜】

在这里插入图片描述
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值