-
Notifications
You must be signed in to change notification settings - Fork 0
/
Word Ladder.cpp
45 lines (40 loc) · 1.16 KB
/
Word Ladder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
using namespace std;
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
unordered_set<string> wordSet(wordList.begin(), wordList.end());
if(!wordSet.count(endWord)) return 0;
queue<string> q{{beginWord}};
int res = 0;
while(!q.empty())
{
for(int k = q.size(); k > 0; k--)
{
string word = q.front();
q.pop();
if(word == endWord) return res+1;
for(int i = 0; i < word.size(); i++)
{
string newWord = word;
for(char ch = 'a'; ch <= 'z'; ch++)
{
newWord[i] = ch;
if(wordSet.count(newWord) && newWord != word)
{
q.push(newWord);
wordSet.erase(newWord);
}
}
}
}
res++;
}
return 0;
}
};