File tree 1 file changed +26
-0
lines changed
solution/0100-0199/0127.Word Ladder
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments