代码拉取完成,页面将自动刷新
// 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;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。