-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_17.22_findLadders.cc
66 lines (60 loc) · 1.39 KB
/
Problem_17.22_findLadders.cc
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
60
61
62
63
64
65
66
#include <queue>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution
{
public:
vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList)
{
unordered_set<string> dict(wordList.begin(), wordList.end());
if (!dict.count(endWord))
{
return {};
}
queue<vector<string>> q;
q.push({beginWord});
dict.erase(beginWord);
while (!q.empty())
{
int size = q.size();
while (size-- > 0)
{
vector<string> path = q.front();
q.pop();
string word = path.back();
for (int i = 0; i < word.size(); ++i)
{
char old = word[i];
for (char ch = 'a'; ch <= 'z'; ++ch)
{
if (ch == old)
{
continue;
}
word[i] = ch;
if (dict.count(word))
{
// 注意,这里不能直接path.push_back(word),因为要尝试不同的可能性
vector<string> next(path);
next.push_back(word);
dict.erase(word);
if (word == endWord)
{
return next;
}
else
{
q.push(next);
}
}
}
// 不要忘记恢复
word[i] = old;
}
}
}
return {};
}
};