Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
分析:一道给力的题,有人说是五星题。采用BFS遍历,并使用vector<string, vector<string> >邻接表来构建图模型,最后使用DFS深度搜索图来得到所有结果。如果遍历图有重复元素,可以使用一个标记为来记录visited。
class Solution {
vector<vector<string> > ret;
string END;
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
END = end;
queue<string> que, next;
que.push(start);
dict.erase(start);
unordered_set<string> del;
del.insert(start);
unordered_map<string, vector<string> > path;
bool found = false;
while(!que.empty()) {
for(auto x : del) dict.erase(x);
del.clear();
while(!que.empty()) {
string x = que.front(); que.pop();
//根据cur查找,并push到next队列
for(int i = 0; i < x.size(); i++) {
string word = x;
for(char ch = 'a'; ch <= 'z'; ch++) {
if(word[i] == ch) continue;
word[i] = ch;
//找到可达字符集合,记录到path中
if(dict.count(word)) {
if(word == end) found = true;
if(!del.count(word))next.push(word);
del.insert(word);
path[x].push_back(word);
}
}
}
}
if(found) break;
swap(que, next);
}
vector<string> item;
item.push_back(start);
DFS(path, start, item);
return ret;
}
private:
void DFS(unordered_map<string, vector<string> > &path, string last, vector<string> &item) {
if(last == END) {
ret.push_back(item);
return ;
}
for(int i = 0; i < path[last].size(); i++) {
item.push_back(path[last][i]);
DFS(path, path[last][i], item);
item.pop_back();
}
}
};