-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
27 lines (27 loc) · 882 Bytes
/
Solution.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
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> words(wordList.begin(), wordList.end());
queue<string> q{{beginWord}};
int ans = 1;
while (!q.empty()) {
++ans;
for (int i = q.size(); i > 0; --i) {
string s = q.front();
q.pop();
for (int j = 0; j < s.size(); ++j) {
char ch = s[j];
for (char k = 'a'; k <= 'z'; ++k) {
s[j] = k;
if (!words.count(s)) continue;
if (s == endWord) return ans;
q.push(s);
words.erase(s);
}
s[j] = ch;
}
}
}
return 0;
}
};