题目:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence 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"]
As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length5.
两个for循环表示将start的每个字母从a遍历到z,同时与end,dict中的单词比较
外层的while循环是每当在dict中找到一个单词时,再从此单词开始
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start.size()!=end.size()) return 0;
if(dict.size()==0) return 0;
queue<string> queuetopush,queuetopop;
queuetopop.push(start);
int distance=1;
while(dict.size()>0&&!queuetopop.empty()){
while(!queuetopop.empty()){
string str(queuetopop.front());
queuetopop.pop();
for(int i=0;i<str.size();i++){
for(char j='a';j<='z';j++){
if(str[i]==j)
continue;
char temp=str[i];
str[i]=j;
if(str==end)
return distance+1;
if(dict.count(str)){
queuetopush.push(str);
dict.erase(str);
}
str[i]=temp;
}
}
}
distance++;
swap(queuetopush,queuetopop);
}
return 0;
}
};