127. Word Ladder

127. Word Ladder_第1张图片
image.png

127. Word Ladder_第2张图片
image.png

转换成BFS做

127. Word Ladder_第3张图片
image.png

参考: http://bangbingsyb.blogspot.com/2014/11/leetcode-word-ladder-i-ii.html

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector& wordList) {
        unordered_set dict;
        for(int i = 0; i < wordList.size(); i++){
            dict.insert(wordList[i]);
        }
        if(!dict.count(endWord)) return 0;
        dict.insert(endWord);
        queue> q;
        q.push(make_pair(beginWord,1));
        while(!q.empty()){
            string cur = q.front().first;
            // cout< 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 findNeighbor(string x, unordered_set& dict){
        vector 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)