-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127.cpp
34 lines (34 loc) · 883 Bytes
/
127.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
// bfs.cpp
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
unordered_map<int, char> map;
int len = 1, n = beginWord.size();
queue<string> qe;
qe.push(beginWord);
unordered_set<string> wordlist(wordList.begin(), wordList.end());
string temp;
while (!qe.empty()) {
int times = qe.size();
for (int k = 0; k < times; ++k) {
temp = qe.front();
if (temp == endWord)
return len;
qe.pop();
for (int i = 0; i < n; ++i) {
char ch = temp[i];
for (int j = 0; j < 26; ++j) {
temp[i] = 'a' + j;
if (wordlist.find(temp) != wordlist.end()) {
qe.push(temp);
wordlist.erase(temp);
}
}
temp[i] = ch;
}
}
len++;
}
return 0;
}
};