127. Word Ladder
BFS, vector, set
Last updated
BFS, vector, set
Last updated
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_map<string, int> cnt;
unordered_set<string> wordSet(wordList.begin(), wordList.end());
queue<string> q;
q.push(beginWord);
cnt[beginWord] = 1;
while (!q.empty()) {
string word = q.front();
q.pop();
for (int i = 0; i < word.size(); i++) {
string newWord = word;
for (char tmp = 'a'; tmp <= 'z'; ++tmp) {
newWord[i] = tmp;
if (wordSet.count(newWord) && newWord == endWord) {
return cnt[word] + 1;
}
if (wordSet.count(newWord) && !cnt[newWord]) {
cnt[newWord] = cnt[word] + 1;
q.push(newWord);
}
}
}
}
return 0;
}
};