-
Notifications
You must be signed in to change notification settings - Fork 0
/
127. Word Ladder.cpp
59 lines (46 loc) · 1.49 KB
/
127. 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// https://leetcode.com/problems/word-ladder/
class Solution
{
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
int numTransformations = 0;
queue<string> nodes;
unordered_set<string> words;
unordered_set<string> visited;
for (string &word : wordList)
words.insert(word);
if (words.find(endWord) == words.end())
return 0;
nodes.push(beginWord);
visited.insert(beginWord);
while (!nodes.empty())
{
numTransformations++;
int size = nodes.size();
for (int i = 0; i < size; ++i)
{
string current = nodes.front();
nodes.pop();
for (int j = 0; j < current.length(); ++j)
{
string temp = current;
for (int k = 0; k < 26; ++k)
{
temp[j] = k + 'a';
if (temp == current || visited.find(temp) != visited.end())
continue;
if (temp == endWord)
return numTransformations + 1;
if (words.find(temp) != words.end())
{
nodes.push(temp);
visited.insert(temp);
}
}
}
}
}
return 0;
}
};