Skip to content

Commit 771a46d

Browse files
Create Word Ladder.cpp
1 parent 531c097 commit 771a46d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Hard Problems/Word Ladder.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//https://leetcode.com/problems/word-ladder/description/
2+
3+
class Solution {
4+
public:
5+
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
6+
unordered_set<string> dict(wordList.begin(), wordList.end());
7+
queue<string> todo;
8+
todo.push(beginWord);
9+
int ladder = 1;
10+
while (!todo.empty()) {
11+
int n = todo.size();
12+
for (int i = 0; i < n; i++) {
13+
string word = todo.front();
14+
todo.pop();
15+
if (word == endWord) {
16+
return ladder;
17+
}
18+
dict.erase(word);
19+
for (int j = 0; j < word.size(); j++) {
20+
char c = word[j];
21+
for (int k = 0; k < 26; k++) {
22+
word[j] = 'a' + k;
23+
if (dict.find(word) != dict.end()) {
24+
todo.push(word);
25+
}
26+
}
27+
word[j] = c;
28+
}
29+
}
30+
ladder++;
31+
}
32+
return 0;
33+
}
34+
};

0 commit comments

Comments
 (0)