Skip to content

Commit 20305fb

Browse files
committed
Time: 72 ms (93.14%), Space: 14 MB (73.67%) - LeetHub
1 parent e5d215f commit 20305fb

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

word-ladder/word-ladder.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public:
3+
int minLenPath(string& beginWord, string& endWord, vector<string>& wordList) {
4+
unordered_set<string> dict(wordList.begin(), wordList.end());
5+
6+
if (dict.find(endWord) == dict.end())
7+
return 0;
8+
queue<pair<string, int>> q;
9+
q.push({beginWord, 1});
10+
dict.erase(beginWord);
11+
12+
while (!q.empty()) {
13+
auto x = q.front();
14+
q.pop();
15+
16+
if (x.first == endWord)
17+
return x.second;
18+
19+
// check its children
20+
string curr = x.first;
21+
for (int i = 0; i < (int)curr.size(); i++) {
22+
char old = curr[i];
23+
24+
for (int j = 0; j < 26; j++) {
25+
if ((j + 'a') == old) continue;
26+
curr[i] = (j + 'a');
27+
28+
if (dict.find(curr) != dict.end()) {
29+
q.push({curr, x.second + 1});
30+
dict.erase(curr);
31+
}
32+
}
33+
34+
curr[i] = old;
35+
}
36+
}
37+
38+
return 0;
39+
}
40+
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
41+
int k = minLenPath(beginWord, endWord, wordList);
42+
return k;
43+
}
44+
};

0 commit comments

Comments
 (0)