题解:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
std::unordered_set<std::string> table(wordList.begin(), wordList.end());
if (table.find(endWord) == table.end()) {
return 0;
}
std::unordered_set<std::string> visited;
std::queue<std::pair<std::string, int>> que;
que.push(std::pair(beginWord, 1));
visited.insert(beginWord);
while (!que.empty()) {
auto f = que.front();
que.pop();
std::string word = f.first;
for (int i = 0; i < word.size(); ++i) {
char c = word[i];
for (int j = 0; j < 26; ++j) {
word[i] = 'a' + j;
if (word == endWord) {
return f.second + 1;
}
if (table.find(word) == table.end()) {
continue;
}
if (visited.find(word) != visited.end()) {
continue;
}
que.push(std::pair(word, f.second+1));
visited.insert(word);
}
word[i] = c;
}
}
return 0;
}
};