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.
其实word ladder是典型的非二维bfs找路径长度,而这个题目就是找出所有能从start到达end的路径
依旧宽搜,但是这里加限制一个条件:bfs时用total变量记录路径的长度,如果第一次到达end,则更新total。如果在宽搜的过程中,当前点的路径长度已经大于total,则对当前点不再进行bfs。
最终得到了一个从start出发的长度范围在total以内路径图,用map<string,int>来维护,其中string记录的是dict里面的单词,int代表它与start之间的路径长度值。
然后,从end开始进行dfs,寻找end到start的路径,用一个vector来记录这个路径里面的单词信息。如果当前点的路径长度值为2,即下一个点就是start,则停止,该路径是一条合法路径。
class Solution {
public:
map<string,int> used;
string queue[10000];
vector<vector<string>> vv;
int step[10000];
int head;
int tail;
int total;
bool valid(string word,unordered_set<string> &dict){
unordered_set<string>::iterator it = dict.find(word);
if(it==dict.end())
return false;
return true;
}
void view(string word,int cur,unordered_set<string> &dict,string end){
if(cur>=total)
return;
string t = word;
for(int i=0;i<t.length();i++){
t=word;
for(int j=0;j<26;j++){
t[i] = j+'a';
if(t==end){
if(total==10000)
total = min(total,cur+1);
return;
}
if(valid(t,dict)){
map<string,int>::iterator it = used.find(t);
if(it->second==-1){
queue[tail] = t;
step[tail++] = cur+1;
it->second = cur+1;
}
}
}
}
}
void build(vector<string> v,string word,int cur,unordered_set<string> &dict){
if(cur==2){
vv.push_back(v);
return;
}
string t = word;
for(int i=0;i<t.length();i++){
t=word;
for(int j=0;j<26;j++){
t[i] = j+'a';
map<string,int>::iterator it = used.find(t);
if(it!=used.end() && it->second==cur-1){
v.insert(v.begin(),it->first);
build(v,it->first,cur-1,dict);
v.erase(v.begin());
}
}
}
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
head = 0;
tail = 0;
total = 10000;
for(unordered_set<string>::iterator it = dict.begin();it!=dict.end();++it){
used.insert(pair<string,int>(*it,-1));
}
queue[tail] = start;
step[tail++] = 1;
while(head!=tail){
string word = queue[head];
int cur = step[head];
head++;
view(word,cur,dict,end);
}
vector<string> v;
v.insert(v.begin(),end);
build(v,end,total,dict);
for(int i=0;i<vv.size();i++)
vv[i].insert(vv[i].begin(),start);
return vv;
}
};
ac
起初我还想,万一目前的路径长度值不是最小的怎么办。。后来再想一想,用bfs从一个点到达一个点的路径长度肯定是最小的。所以,第一个到达end的路径长度肯定就是最小的,即最终要求的合法路径长度。