问题描述:
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.
代码:
void createResult(map<string,vector<string> >&record,vector<vector<string> >&result,string pre,string start,list<string>myList){ //C++
if(pre == start){
vector<string> vec(myList.begin(),myList.end());
result.push_back(vec);
// for(int i=0; i<myList.size();i++)
// vec.push_back(myList[i]);
}
vector<string> next = record[pre];
for(int i=0; i<next.size(); i++){
string word = next[i];
list<string> temp(myList);
temp.push_front(word);
createResult(record,result,word,start,temp);
}
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string> > result;
int size = dict.size();
if(start.size() ==0 || end.size() ==0 || size==0 || start==end)
return result;
map<string,int> myMap;
map<string,vector<string> > record;
queue<string> myQueue;
myQueue.push(start);
myMap[start] = 1;
string temp;
while(!myQueue.empty()){
temp = myQueue.front();
myQueue.pop();
for(int i =0; i<temp.size(); i++){
string newword = temp;
for(int j=0; j<26; j++){
newword[i] = 'a'+j;
if(dict.count(newword)!=0){
if(myMap.count(newword)==0)
{
myMap[newword] = myMap[temp] +1;
myQueue.push(newword);
vector<string> vec;
vec.push_back(temp);
record.insert(make_pair(newword,vec));
}
else if(myMap[newword] == myMap[temp]+1){
vector<string> vec = record[newword];
vec.push_back(temp);
record[newword]=vec;
}
}
}
}
}
if(record.count(end)==0)
return result;
list<string> temp_list;
temp_list.push_back(end);
createResult(record,result,end,start,temp_list);
}