题解 | #玛雅人的密码#

BFS搜索

set<string> visited;
int BFS(string str,string eam)
{
    queue<pair<string, int> > myQueue;
    myQueue.push(make_pair(str, 0));//压入初始点
    visited.insert(str);
    while (!myQueue.empty())
    {
        string curt = myQueue.front().first;//获取当前点
        int t = myQueue.front().second;
        myQueue.pop();
        if (strstr(curt.c_str(), eam.c_str()))//满足规定值,退出
        {
            return t;
        }
        for (int i = 0; i < curt.size() - 1; i++)//状态变换
        {
            string next = curt;
            swap(next[i], next[i + 1]);
            if (visited.count(next))
            {
                continue;
            }
            myQueue.push(make_pair(next, t + 1));
            visited.insert(next);
        }
    }
    return -1;
}
全部评论

相关推荐

黑着眼圈看手机:pdd秋招笔试挂了,春招还行吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务