-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127. Word Ladder.cpp
44 lines (44 loc) · 1.59 KB
/
127. Word Ladder.cpp
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
37
38
39
40
41
42
43
44
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
std::unordered_set<std::string> wordlistSet;
for(auto word : wordList) {
wordlistSet.insert(word);
}
std::unordered_set<std::string> nextSet;
std::unordered_set<std::string> currSet;
currSet.insert(beginWord);
int count = 1;
string current_word = beginWord;
int n = beginWord.size();
while(!currSet.empty())
{
for(auto s : currSet)
{
for(int i = 0; i < n; ++i)
{
string temp = s;
for(int j = 0; j < 26; ++j)
{
temp[i] = 'a' + j;
auto it = wordlistSet.find(temp);
if(it != wordlistSet.end())
{
if(temp == endWord)
return count+1;
nextSet.insert(temp);
wordlistSet.erase(temp); //it
}
}
}
}
++count;
currSet = nextSet;
nextSet.clear();
}
return 0;
}
};