-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127. Word Ladder
36 lines (36 loc) · 1.2 KB
/
127. Word Ladder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//https://leetcode.com/problems/word-ladder/
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordDict(wordList.begin(), wordList.end());
queue<string> toVisit;
addNextWords(beginWord, wordDict, toVisit);
int dist = 2;
while (!toVisit.empty()) {
int num = toVisit.size();
for (int i = 0; i < num; i++) {
string word = toVisit.front();
toVisit.pop();
if (word == endWord) return dist;
addNextWords(word, wordDict, toVisit);
}
dist++;
}
return 0;
}
private:
void addNextWords(string word, unordered_set<string>& wordDict, queue<string>& toVisit) {
wordDict.erase(word);
for (int p = 0; p < (int)word.length(); p++) {
char letter = word[p];
for (int k = 0; k < 26; k++) {
word[p] = 'a' + k;
if (wordDict.find(word) != wordDict.end()) {
toVisit.push(word);
wordDict.erase(word);
}
}
word[p] = letter;
}
}
};