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>> ret; map<string,int> level;//每个词都有一个层次,层次要尽可能小 map<string,vector<string>> father;//前驱节点 vector<string> temp; father[start]=temp; for(auto i=dict.begin();i!=dict.end();i++) { level[*i]=-1; } level[start]=1; level[end]=-1; dict.insert(end); queue<string> q; q.push(start); while(!q.empty()) { string cur=q.front(); string origi=cur; if(level[end]!=-1 && level[cur]>=level[end]) break; q.pop(); for(int i=0;i<cur.size();i++) { //for each char for(char j='a';j<='z';j++) { if(origi[i]!=j) { cur[i]=j; if(dict.count(cur)) { if(level[cur]==-1) { father[cur].push_back(origi); level[cur]=level[origi]+1; q.push(cur); } else if(level[cur]==level[origi]+1) { father[cur].push_back(origi); } } } cur=origi; } } } //由father生成路径 if(!father[end].empty()) { ret=gen_path(end,father); for(int i=0;i!=ret.size();i++) { reverse(ret[i].begin(),ret[i].end()); } } return ret; } vector<vector<string>> gen_path(string point,map<string,vector<string>> &father) { vector<vector<string>> ret; if(father[point].empty()) { vector<string> ta; ta.push_back(point); ret.push_back(ta); return ret; } else { for(int i=0;i!=father[point].size();i++) { vector<vector<string>> oth=gen_path(father[point][i],father); for(int j=0;j!=oth.size();j++) { vector<string> temp; temp.push_back(point); temp.insert(temp.end(),oth[j].begin(),oth[j].end()); ret.push_back(temp); } } return ret; } } };