File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -266,6 +266,44 @@ class Solution {
266
266
}
267
267
```
268
268
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
+
269
307
### Conclusion
270
308
* How to choose dfs and bfs
271
309
1. bfs is designed for shortest path question.
You can’t perform that action at this time.
0 commit comments