Word Ladder II
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,得到father,记录广度搜索路径上,每一个节点的父节点(可以有多个)
因此采用 unordered_map<string,unordered_set<string>> 数据结构
例如father["aaa"]=["baa","caa"]表示了aaa在广度优先搜素路径上的父节点为"baa","caa";
广度优先搜索时,从start开始,
找到与start相邻的节点 node1,node2,.....;
并记录每一个节点的父节点为start
然后从node1,node2...开始,遍历下一层
直到找到end节点停止(注意,必须上一层节点全部遍历完
找到father 路径后,从end开始往前dfs就可以得到所有的结果了
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string>> result;
unordered_set<string> unvisited=dict; dict.insert(start);
dict.insert(end); unordered_map<string,unordered_set<string>> father;
if(unvisited.count(start)==) unvisited.erase(start); unordered_set<string> curString,nextString;
curString.insert(start); while(curString.count(end)==&&curString.size()>)
{ for(auto it=curString.begin();it!=curString.end();it++)
{
string word=*it;
for(int i=;i<word.length();i++)
{
string tmp=word;
for(int j='a';j<='z';j++)
{
if(tmp[i]==j) continue;
tmp[i]=j;
if(unvisited.count(tmp)>)
{
nextString.insert(tmp);
father[tmp].insert(word); } }
}
} if(nextString.size()==) break; for(auto it=nextString.begin();it!=nextString.end();it++)
{
//必须遍历完了curString中所有的元素,才能在unvisited中删除(因为可能有多个父节点对应着该节点)
unvisited.erase(*it);
} curString=nextString;
nextString.clear(); } if(curString.count(end)>)
{
vector<string> tmp;
dfs(father,end,start,result,tmp);
} return result;
} void dfs(unordered_map<string,unordered_set<string>> &father,string end,string start,vector<vector<string>> &result,vector<string> tmp)
{
tmp.push_back(end);
if(end==start)
{
reverse(tmp.begin(),tmp.end());
result.push_back(tmp);
return;
} for(auto it=father[end].begin();it!=father[end].end();it++)
{
dfs(father,*it,start,result,tmp);
}
}
};