Skip to content

Commit 02d3802

Browse files
authored
127. Word Ladder
1 parent 646c188 commit 02d3802

File tree

1 file changed

+26
-15
lines changed

1 file changed

+26
-15
lines changed

cpp/121-130/Word Ladder.cpp

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,38 @@
1+
2+
13
class Solution {
24
public:
35
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
46
unordered_set<string> dict(begin(wordList), end(wordList));
5-
unordered_map<string, int> dis; // store the distance from start to the current word
6-
queue<string> q; // FIFO for bfs purpose
7-
dis[beginWord] = 1;
7+
queue<string> q;
88
q.push(beginWord);
9+
unordered_set<string> visited;
10+
visited.insert(beginWord);
11+
int step = 1;
912
while (!q.empty()) {
10-
string word = q.front();
11-
q.pop();
12-
if (word == endWord) break;
13-
for (int i = 0; i < word.size(); i++) {
14-
for (int j = 0; j < 26; j++) {
15-
string newWord = word;
16-
newWord[i] = 'a' + j;
17-
if (dict.count(newWord) > 0 && dis.count(newWord) == 0) {
18-
dis[newWord] = dis[word] + 1;
19-
q.push(newWord);
13+
int k = q.size();
14+
for (int i = 0; i < k; i++) {
15+
string word = q.front();
16+
q.pop();
17+
if (word == endWord) {
18+
return step;
19+
}
20+
for (int i = 0; i < word.size(); i++) {
21+
char ch = word[i];
22+
for (int j = 0; j < 26; j++) {
23+
word[i] = 'a' + j;
24+
if (visited.count(word) == 0 && dict.count(word) > 0) {
25+
visited.insert(word);
26+
q.push(word);
27+
}
2028
}
29+
word[i] = ch;
2130
}
2231
}
32+
33+
step++;
2334
}
24-
if (dis.count(endWord) == 0) return 0;
25-
return dis[endWord];
35+
36+
return 0;
2637
}
2738
};

0 commit comments

Comments
 (0)