题目描述
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.
以下代码超时:
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> result;
vector<string> path;
bool found = false;
unordered_set<string> visited;
unordered_map<string, unordered_set<string>> father;
queue<string> current, next;
if(start.size() != end.size()) return result;current.push(start);
while(!current.empty())
{
string str=current.front();
current.pop();
string a = str;
for(int i=0; i<str.size(); ++i)
{
char tmp=str[i];
for(char c='a' ;c<='z'; ++c)
{
if(c == tmp) continue;
str[i]=c;
if(str == end)
{
found = true;
break;
}
if(dict.find(str)!= dict.end() && !visited.count(str))
{
visited.insert(str);
next.push(str);
father[str].insert(a);
}
str[i]=tmp;
}
}// end for
if(current.empty() && !found) current=next;
}// end while
buildPath(father, path, start, end, result);
return result;
}
void buildPath( unordered_map<string, unordered_set<string>> &father, vector<string> &path, const string &start, const string &end, vector<vector<string> > &result)
{
path.push_back(end);
if(end == start)
{
result.push_back(path);
reverse(result.back().begin(), result.back().end());
}
else
{
for(auto f : father[end])
buildPath(father, path, start, f, result);
}
path.pop_back();
}
};