码迷,mamicode.com
首页 > 其他好文 > 详细

LC 127. Word Ladder (two end bfs)

时间:2020-02-09 11:19:33      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:lis   int   class   str   tin   ring   eve   png   alt   

Link

技术图片

 

 

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> words;
        for(auto &s:wordList){
            words.insert(s);
        }
        if(words.find(endWord)==words.end()) return 0;
        unordered_set<string> beginSet;
        unordered_set<string> endSet;
        beginSet.insert(beginWord);
        endSet.insert(endWord);
        unordered_set<string> visited;
        visited.insert(beginWord);
        visited.insert(endWord);
        int level=1;
        while(!beginSet.empty() && !endSet.empty()){
            if(beginSet.size()>endSet.size()){
                auto tmp=beginSet;
                beginSet=endSet;
                endSet=tmp;
            }
            unordered_set<string> tmp;
            for(auto s:beginSet){
                for(int i=0;i<s.size();++i){
                    char bk=s[i];
                    for(char c=a;c<=z;++c){
                        if(c==bk) continue;
                        s[i]=c;
                        if(endSet.find(s)!=endSet.end()) return level+1;
                        if(visited.find(s)==visited.end() && words.find(s)!=words.end()){
                            visited.insert(s);
                            tmp.insert(s);
                        }
                    }
                    s[i]=bk;
                }
            }
            beginSet=tmp;
            ++level;
        }
        return 0;
    }
};

 

LC 127. Word Ladder (two end bfs)

标签:lis   int   class   str   tin   ring   eve   png   alt   

原文地址:https://www.cnblogs.com/FEIIEF/p/12286268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!