Skip to content

Commit 4ea4941

Browse files
committed
[Function add]
1. Add leetcode solutions using C++.
1 parent 6219841 commit 4ea4941

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: leetcode/127. Word Ladder.md

+38
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,44 @@ class Solution {
266266
}
267267
```
268268

269+
### C++ Version
270+
* Method 1: bi-directional bfs
271+
```objectivec
272+
class Solution {
273+
public:
274+
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
275+
unordered_set<string> set(wordList.begin(), wordList.end());
276+
if(set.find(endWord) == set.end()) return 0;
277+
set.erase(endWord);
278+
unordered_set<string> first{beginWord}, second{endWord};
279+
int len = endWord.length();
280+
int step = 0;
281+
while(!first.empty() && !second.empty()){
282+
++step;
283+
if(first.size() > second.size())
284+
std::swap(first, second);
285+
unordered_set<string> next;
286+
for(string cur: first){
287+
for(int i = 0; i < len; ++i){
288+
char origin = cur[i];
289+
for(char c = 'a'; c <= 'z'; ++c){
290+
cur[i] = c;
291+
if(second.find(cur) != second.end()) return step + 1;
292+
if(set.find(cur) != set.end()){
293+
next.emplace(cur);
294+
set.erase(cur);
295+
}
296+
cur[i] = origin;
297+
}
298+
}
299+
}
300+
std::swap(next, first);
301+
}
302+
return 0;
303+
}
304+
};
305+
```
306+
269307
### Conclusion
270308
* How to choose dfs and bfs
271309
1. bfs is designed for shortest path question.

0 commit comments

Comments
 (0)