forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-ladder-ii.cpp
79 lines (76 loc) · 2.79 KB
/
word-ladder-ii.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Time: O(b^(d/2)), b is the branch factor of bfs, d is the result depth
// Space: O(w * l), w is the number of words, l is the max length of words
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> words(cbegin(wordList), cend(wordList));
if (!words.count(endWord)) {
return {};
}
unordered_map<string, unordered_set<string>> tree;
unordered_set<string> left = {beginWord}, right = {endWord};
bool is_found = false, is_reversed = false;
while (!empty(left)) {
for (const auto& word : left) {
words.erase(word);
}
unordered_set<string> new_left;
for (const auto& word : left) {
auto new_word = word;
for (int i = 0; i < size(new_word); ++i) {
char prev = new_word[i];
for (int j = 0; j < 26; ++j) {
new_word[i] = 'a' + j;
if (!words.count(new_word)) {
continue;
}
if (right.count(new_word)) {
is_found = true;
} else {
new_left.emplace(new_word);
}
if (!is_reversed) {
tree[new_word].emplace(word);
} else {
tree[word].emplace(new_word);
}
}
new_word[i] = prev;
}
}
if (is_found) {
break;
}
left = move(new_left);
if (size(left) > size(right)) {
swap(left, right);
is_reversed = !is_reversed;
}
}
return backtracking(tree, beginWord, endWord);
}
private:
vector<vector<string>> backtracking(
const unordered_map<string, unordered_set<string>>& tree,
const string& beginWord,
const string& word) {
vector<vector<string>> result;
if (word == beginWord) {
result.emplace_back(vector<string>({beginWord}));
} else {
if (tree.count(word)) {
for (const auto& new_word : tree.at(word)) {
if (word == new_word) {
continue;
}
auto paths = backtracking(tree, beginWord, new_word);
for (auto& path : paths) {
path.emplace_back(word);
result.emplace_back(move(path));
}
}
}
}
return result;
}
};