您的位置:首页 > 其它

leetcode[126]Word Ladder II

2015-02-09 13:11 417 查看
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:
void dfs(vector<vector<string>> &res,vector<string> str,unordered_map<string,vector<string>> &father,string start, string now)
{
if(now==start)
{
str.push_back(now);
res.push_back(str);
reverse(res.back().begin(),res.back().end());
return;
}
for(const auto &x : father[now])
{
str.push_back(now);
dfs(res,str,father,start,x);
str.pop_back();
}
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> res;
if(start==end)return res;
unordered_set<string> curr,next;
unordered_set<string> all;
unordered_map<string,vector<string>> father;
bool found=false;
curr.insert(start);
while(!curr.empty()&&!found)
{
for(const auto &x : curr)
{
all.insert(x);
}
for(const auto &x : curr)
{
for(int i=0;i<x.length();i++)
{
for(char j='a';j<='z';j++)
{
if(x[i]==char(j))continue;
string tx=x;
tx[i]=char(j);
if(tx==end)found=true;
if(dict.find(tx)!=dict.end()&&all.find(tx)==all.end())
{
next.insert(tx);
father[tx].push_back(x);
}
}
}
}
curr.clear();
swap(curr,next);
}
vector<string> str;
dfs(res,str,father,start,end);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: