Leetcode 127. 单词接龙

Posted randyniu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 127. 单词接龙相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    //两个字符串是否可以相互转换
    bool connect(const string &word1, const string &word2)
    {
        int cnt = 0;
        for(int i=0; i<word1.size(); ++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_graph(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> &neighbors = graph[node];
            
            for(int i=0; i<neighbors.size(); ++i)
            {
                if(visit.find(neighbors[i]) == visit.end())
                {
                    q.push(make_pair(neighbors[i], step+1));
                    visit.insert(neighbors[i]);
                }
            }   
        }
        
        return 0;
    }
                   
                   
    int ladderLength(string beginWord, string endWord, vector<string>& wordList)
    {
        map<string, vector<string>>  graph;
        construct_graph(beginWord, wordList, graph);
        return BFS_graph(beginWord, endWord, graph);
    }
};

 

以上是关于Leetcode 127. 单词接龙的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 127. 单词接龙

Leetcode 127. 单词接龙

Leetcode No.127 单词接龙(BFS)

Leetcode No.127 单词接龙(BFS)

(Java) LeetCode 127. Word Ladder —— 单词接龙

题目地址(127. 单词接龙)