思路:
记录每个节点的父节点,BFS完成后通过DFS找到所有的路径。
第一次MLE。
class Solution {
private:
unordered_map<string, vector<string>> father;
vector<vector<string>> res;
void dfs(vector<string> &path, string &start, string &end) {
path.push_back(end);
if(start == end) {
res.push_back(path);
reverse(res.back().begin(), res.back().end());
path.pop_back();
return;
}
vector<string> pre_words = father.find(end)->second;
for(int i = 0; i < pre_words.size(); ++i) {
dfs(path, start, pre_words[i]);
}
path.pop_back();
}
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
if(start == end) return res;
queue<string> level_words;//bfs every level's words
level_words.push(start);
int count = 1;
dict.erase(start);
bool found = false;
unordered_set<string> current_visit;
while(!level_words.empty()) {
string cur_word = level_words.front();
level_words.pop();
count--;
for(int i = 0; i < cur_word.size(); ++i) {
string tmp_word = cur_word;
for(char c = 'a'; c <= 'z'; ++c) {
if(tmp_word[i] == c) continue;
tmp_word[i] = c;
if(tmp_word == end) {
found = true;
father[tmp_word].push_back(cur_word);
}
if(dict.find(tmp_word) != dict.end()) {
level_words.push(tmp_word);
father[tmp_word].push_back(cur_word);
current_visit.insert(tmp_word);
}
}
}
if(count == 0) {
count = level_words.size();
for(auto w : current_visit) {
dict.erase(w);
}
current_visit.clear();
}
}
if(found) {
vector<string> path;
dfs(path, start, end);
}
return res;
}
};
然后,参考了别人的实现,不用维护队列。
class Solution {
private:
unordered_map<string, vector<string>> father;
vector<vector<string>> res;
void dfs(vector<string> &path, string &start, string &end) {
path.push_back(end);
if(start == end) {
res.push_back(path);
reverse(res.back().begin(), res.back().end());
path.pop_back();
return;
}
vector<string> pre_words = father.find(end)->second;
for(int i = 0; i < pre_words.size(); ++i) {
dfs(path, start, pre_words[i]);
}
path.pop_back();
}
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
if(start == end) return res;
bool found = false;
unordered_set<string> current_visit, next;
unordered_set<string> flag;
current_visit.insert(start);
while(!current_visit.empty() && !found) {
for(const auto word : current_visit) {
flag.insert(word);
}
for(auto word : current_visit) {
for(int i = 0; i < word.size(); ++i) {
for(char c = 'a'; c <= 'z'; ++c) {
if(word[i] == c) continue;
string tmp = word;
tmp[i] = c;
if(tmp == end) {
found = true;
//father[tmp].push_back(word);
}
if(dict.find(tmp) != dict.end() && flag.find(tmp) == flag.end()) {
next.insert(tmp);
father[tmp].push_back(word);
}
}
}
}
current_visit.clear();
swap(current_visit, next);
}
if(found) {
vector<string> path;
dfs(path, start, end);
}
return res;
}
};
leetcode的test case应该是start和end都是dict的一部分,否则如果start和end不属于dict的话,第二个if进不去,所以应该在第一个if添加最后的节点关系(即注释的部分)。