Word Ladder II
https://leetcode.com/problems/word-ladder-ii/description/
Thoughts
Code
/*
* @lc app=leetcode id=126 lang=cpp
*
* [126] Word Ladder II
*/
class Solution {
public:
unordered_map<string, unordered_set<string>> bfs(unordered_set<string> &words, const string start, const string end) {
unordered_set<string> q1({start});
unordered_set<string> q2({end});
unordered_map<string, unordered_set<string>> childrens;
bool found = false, backward = false;
while (!q1.empty() && !q2.empty() && !found) {
for (const auto &w : q1) words.erase(w);
for (const auto &w : q2) words.erase(w);
unordered_set<string> nq;
if (q1.size() > q2.size()) {
swap(q1, q2);
backward = !backward;
}
for (const auto &t : q1) {
auto w = t;
for (int i = 0; i < t.size(); ++i) {
const char ch = w[i];
for (char c = 'a'; c <= 'z'; ++c) {
w[i] = c;
const auto *parent = &t;
const auto *child = &w;
if (backward) swap(parent, child);
if (q2.count(w)) {
found = true;
childrens[*parent].insert(*child);
} else if (words.count(w)) {
childrens[*parent].insert(*child);
nq.insert(w);
}
}
w[i] = ch;
}
}
swap(q1, nq);
}
return childrens;
}
void dfs(unordered_map<string, unordered_set<string>> &childrens, const string end, const string cur, vector<string> &path, vector<vector<string>> &res) {
if (cur == end) {
res.push_back(path);
return;
}
for (const auto &c : childrens[cur]) {
path.push_back(c);
dfs(childrens, end, c, path, res);
path.pop_back();
}
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> words(wordList.begin(), wordList.end());
if (!words.count(endWord)) return {};
auto childrens = bfs(words, beginWord, endWord);
vector<string> path({beginWord});
vector<vector<string>> res;
dfs(childrens, endWord, beginWord, path, res);
return res;
}
};
Analysis
Ver.2
Analysis
Last updated