Skip to content

Commit 023afbf

Browse files
authored
Merge pull request doocs#330 from Stackingrule/dev
feat:add Solution.cpp for 0127. Word Ladder
2 parents 87ea417 + dd01e7d commit 023afbf

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
4+
unordered_set<string> wordSet(wordList.begin(), wordList.end());
5+
if (!wordSet.count(endWord))
6+
return 0;
7+
unordered_map<string, int> pathCnt{{{beginWord, 1}}};
8+
queue<string> q{{beginWord}};
9+
while (!q.empty()) {
10+
string word = q.front();
11+
q.pop();
12+
for (int i = 0; i < word.size(); ++i) {
13+
string newWord = word;
14+
for (char ch = 'a'; ch <= 'z'; ++ch) {
15+
newWord[i] = ch;
16+
if (wordSet.count(newWord) && newWord == endWord) return pathCnt[word] + 1;
17+
if (wordSet.count(newWord) && !pathCnt.count(newWord)) {
18+
q.push(newWord);
19+
pathCnt[newWord] = pathCnt[word] + 1;
20+
}
21+
}
22+
}
23+
}
24+
return 0;
25+
}
26+
};

0 commit comments

Comments
 (0)