class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> s(wordList.begin(), wordList.end());
if (s.find(endWord) == s.end() || beginWord == endWord) return 0;
queue<string> q;
q.push(beginWord);
s.erase(beginWord);
int lv = 1;
while (!q.empty()) {
lv++;
int qs = q.size();
while (qs-- > 0) {
beginWord = q.front();
q.pop();
for (int i = 0; i < beginWord.length(); i++) {
char back = beginWord[i];
for (char c = 'a'; c <= 'z'; c++) {
beginWord[i] = c;
if (beginWord == endWord)
return lv;
if (s.find(beginWord) == s.end())
continue;
s.erase(beginWord);
q.push(beginWord);
}
beginWord[i] = back;
}
}
}
return 0;
}
};