Skip to content

Commit 453d955

Browse files
committed
word_ladder
1 parent 837222b commit 453d955

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
109109
#### [120. triangle](https://github.com/hitzzc/go-leetcode/tree/master/triangle)
110110
#### [124. binary tree maximum path sum](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_maximum_path_sum)
111111
#### [125. valid palindrome](https://github.com/hitzzc/go-leetcode/tree/master/valid_palindrome)
112+
#### [127. word ladder](https://github.com/hitzzc/go-leetcode/tree/master/word_ladder)
112113

113114

114115

word_ladder/word_ladder.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <queue>
2+
#include <unordered_set>
3+
#include <map>
4+
#include <string>
5+
using namespace std;
6+
7+
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
8+
if (beginWord == endWord)
9+
return 1;
10+
if (distance(beginWord, endWord)==1)
11+
return 2;
12+
map<string, int> dist;
13+
dist[beginWord] = 1;
14+
queue<string> q;
15+
q.push(beginWord);
16+
while (!q.empty()){
17+
string word = q.front();
18+
q.pop();
19+
if (word == endWord) return dist[word];
20+
if (wordList.size() < 26*word.size()){
21+
for (auto& w: wordList){
22+
if (dist.find(w)==dist.end() && distance(word, w)==1){
23+
dist[w] = dist[word] + 1;
24+
q.push(w);
25+
}
26+
}
27+
}else{
28+
for (int i = 0; i < word.size(); ++i){
29+
string temp = word;
30+
for (int j = 'a'; j <= 'z'; ++j){
31+
temp[i] = j;
32+
if (wordList.find(temp)!=wordList.end() && dist.find(temp)==dist.end()){
33+
dist[temp] = dist[word] + 1;
34+
q.push(temp);
35+
}
36+
}
37+
}
38+
}
39+
}
40+
return 0;
41+
}
42+
43+
int distance(string dist, string src){
44+
int count = 0;
45+
for (int i = 0; i < dist.size(); ++i){
46+
if (dist[i]!=src[i]) ++count;
47+
}
48+
return count;
49+
}

0 commit comments

Comments
 (0)