版权声明:版权归作者所有,转发请标明 https://blog.csdn.net/weixin_40087851/article/details/82021174
问题描述
- 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. - Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.翻译
- 给定两个单词(开头和结尾)和一个字典,找到从开始到结束的最短变换序列的长度,一次只能更改一个字母,每个中间词必须存在于字典中。
- 给定:start =“hit”;结束=“cog”;dict = [“hot”,“dot”,“dog”,“lot”,“log”]
- 一个最短的转变是“hit” - >“hot” - >“dot” - >“dog” - >“cog”,返回长度5。
- 注意:如果没有这样的转换序列,则返回0。所有单词都有相同的长度。所有单词仅包含小写字母字符。
分析
寻找最短变化序列的长度,相当于是寻找最短路径,我们可以想到广度优先遍历算法和深度优先遍历算法。
变换单词:每一位上的字符都有可能改变,每一个字符都对应a~z。
对于广度优先遍历,即层层向外扩展,与当前单词有关的单词都需要考虑。因此当我们使用队列时,先判断变换之后的单词是否与结束单词相同,若相同,则结束;若不同,则判断变换之后的单词是否存在于字典中,若存在,入队列,并将其在字典中删除,防止重复计算。
代码段
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
queue<string> q;
q.push(start);
int length=1;
while(!q.empty()){
int size=q.size();
while(size--){
string cur=q.front();
q.pop();
for(int i=0;cur[i]!='\0';++i){
char c=cur[i];
for(int j=0;j<26;++j){
cur[i]='a'+j;
if(cur==end)
return length+1;
if(dict.find(cur)!=dict.end()){
q.push(cur);
dict.erase(cur);
}
}
cur[i]=c;
}
}
++length;
}
return 0;
}
};