美文网首页
127. Word Ladder

127. Word Ladder

作者: 刘小小gogo | 来源:发表于2018-09-23 21:57 被阅读0次
image.png
image.png

转换成BFS做

image.png
参考:http://bangbingsyb.blogspot.com/2014/11/leetcode-word-ladder-i-ii.html
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> dict;
        for(int i = 0; i < wordList.size(); i++){
            dict.insert(wordList[i]);
        }
        if(!dict.count(endWord)) return 0;
        dict.insert(endWord);
        queue<pair<string, int>> q;
        q.push(make_pair(beginWord,1));
        while(!q.empty()){
            string cur = q.front().first;
            // cout<<cur<<endl;
            int len = q.front().second;
            q.pop();
            vector<string> nb = findNeighbor(cur, dict);
            for(int i = 0; i < nb.size(); i++){
                if(nb[i] == endWord) return len+1;
                q.push(make_pair(nb[i], len+1));
            }
        }
        return 0;
    }
private:
    vector<string> findNeighbor(string x, unordered_set<string>& dict){
        vector<string> ret;
        for(int i = 0; i < x.length(); i++){
            char ch = x[i];
            for(int j = 0; j < 26; j++){
                x[i] = 'a' + j;
                if(dict.count(x)){
                    ret.push_back(x);
                    dict.erase(x);
                }
            }
            x[i] = ch;
        }
        return ret;
    }
};

相关文章

网友评论

      本文标题:127. Word Ladder

      本文链接:https://www.haomeiwen.com/subject/ijwqoftx.html