题目:
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
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:
DFS:
class Solution {
private:
vector<vector<string> > pathes;
map<string,int> travesed; //创建一个map用来记录已经访问过的节点
private:
bool canBeChanged(string str1, string str2){
int eq = 0;
int i;
int ls1 = str1.size();
int ls2 = str2.size();
if(ls1 != ls2)return false;
for(i = 0; i < str1.size(); i++){
if(str1[i] != str2[i])eq++;
}
if(eq == 1)return true;
return false;
}
void BFS(queue<string>& breath, vector<string>& tmp, unordered_set<string> &dict, string end, int level){
if(breath.empty() == false){
string cur = breath.front();
breath.pop();
tmp.push_back(cur);
if(canBeChanged(cur,end)){
//找到一条
tmp.push_back(end);
pathes.push_back(tmp);
//回溯
tmp.pop_back();
return;
}
for(const string& x:dict){
map<string, int>::iterator it;
it = travesed.find(x);
if(it == travesed.end() || travesed[x] == 0){
if(canBeChanged(cur,x)){
travesed[x] = 1;
breath.push(x);
BFS(breath, tmp, dict, end, level+1);
//回溯
travesed[x] = 0;
tmp.pop_back();
}
}
}
}
}
public:
//bfs
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
queue<string> breath;
breath.push(start);
vector<string> tmp;
travesed[start] = 1;
BFS(breath, tmp, dict, end, 0);
vector<vector<string>> res;
vector<vector<string>>::iterator it1;
int max = INT_MAX;
for(it1 = pathes.begin(); it1 != pathes.end(); it1++){
if(max > it1->size()){
max = it1->size();
}
}
for(it1 = pathes.begin(); it1 != pathes.end(); it1++){
if(max == it1->size()){
res.push_back(*it1);
}
}
return res;
}
};
不过超时了。因为每一次递归都遍历了整个dic。之所以用递归,是因为在遍历的同时要记录路径,想办法不用递归也能记录路径,应该能解决这个问题。
原文:http://www.cnblogs.com/zhutianpeng/p/4299079.html