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;
}
};