BFS之单词最少转换次数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BFS之单词最少转换次数相关的知识,希望对你有一定的参考价值。

#include<iostream>
#include<set>
#include<queue>
#include<vector>
#include<string>
#include<map>
using namespace std;
bool connect(string &word1,string &word2)
{
    int cnt = 0;
    for(int i = 0; i < word1.length(); i++)
    if(word1[i] != word2[i])
    cnt++;
    return cnt == 1;
}
void construct_graph(string &beginword,vector<string> &wordlist, map<string ,vector<string> > &graph)
{
    wordlist.push_back(beginword);
    for(int i = 0; i < wordlist.size(); i++)
    graph[wordlist[i]] = vector<string>();

    for(int i = 0; i < wordlist.size(); i++)
        for(int j = i+1; j < wordlist.size(); j++)
    {
        if(connect(wordlist[i],wordlist[j]))
        {
            graph[wordlist[i]].push_back(wordlist[j]);
            graph[wordlist[j]].push_back(wordlist[i]);
        }
     } 
}
int BFS_wordlist(string &beginword, string &endword, map<string, vector<string> > &graph)
{
    queue<pair<string,int> > q;
    set<string> visit;
    q.push(make_pair(beginword,1));
    visit.insert(beginword);
    while(!q.empty())
    {
        string node = q.front().first;
        int step = q.front().second;
        q.pop();
        if(node == endword)
        {
            return step;
        }

        vector<string> brothers = graph[node];
        for(int i = 0; i < brothers.size(); i++)
        {
            if(visit.find(brothers[i]) == visit.end())
            {
                q.push(make_pair(brothers[i], step+1));
                visit.insert(brothers[i]);
            }
        }
    }
    return 0;
}
int main()
{
    string beginword,endword;
    vector<string> wordlist;
    map<string ,vector<string> > graph;
    wordlist.push_back("hot");
    wordlist.push_back("dot");
    wordlist.push_back("dog");
    wordlist.push_back("lot");
    wordlist.push_back("log");
    wordlist.push_back("cog");
    cin>>beginword;
    cin>>endword;
    construct_graph(beginword,wordlist,graph);
    cout<<BFS_wordlist(beginword,endword,graph);
    return 0;
}

以上是关于BFS之单词最少转换次数的主要内容,如果未能解决你的问题,请参考以下文章

NYOJ21.三个水杯-初始态到目标态的最少次数-经典BFS

NYOJ 353 3D dungeon bfs

华为python机试题目:整数与IP地址间的转换图片整理字串的连接最长路径查找提取不重复的整数字符串合并处理字符串最后一个单词的长度删除字符串中出现次数最少的字符

华为机试题 HJ23删除字符串中出现次数最少的字符

LeetCode-BFS单词接龙

bfs输出路径 && 最短路(迪杰斯特拉)输出路径