-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path127.cpp
More file actions
39 lines (39 loc) · 1.17 KB
/
Copy path127.cpp
File metadata and controls
39 lines (39 loc) · 1.17 KB
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
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
int n = beginWord.size(), count = 0;
if (n != endWord.size())
return 0;
unordered_map<string, bool> words;
for (auto &l:wordList)
words[l] = true;
queue<string> que;
int size = 1;
que.push(beginWord);
string word = que.front();
while (!que.empty()) {
word = que.front();
if (word == endWord)
break;
que.pop();
for (int i = 0; i < word.size(); ++i) {
string temp = word;
for (int j = 0; j < 26; ++j) {
if ('a' + j == word[i])
continue;
temp[i] = 'a' + j;
if (words.find(temp) != words.end()) {
que.push(temp);
words.erase(temp);
}
}
}
--size;
if (size == 0) {
size = que.size();
++count;
}
}
return word == endWord ? count + 1 : 0;
}
};