给定两个单词(初始单词和目标单词)和一个单词字典,请找出所有的从初始单词到目标单词的最短转换序列的长度:
例如:
给定的初始单词start="hit",
目标单词end ="cog"。
单词字典dict =["hot","dot","dog","lot","log"]
一个最短的转换序列为"hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回长度5
注意:
如果没有符合条件的转换序列,返回0。
题目中给出的所有单词的长度都是相同的
题目中给出的所有单词都仅包含小写字母
Given two words (start and end), and a dictionary, find the length of
shortest transformation sequence from start to end, such that:
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.
class Solution {
public:
int ladderLength(string start, string end, unordered_set
queue
Q.push(start);
int res=1;
while (!Q.empty()){
int qsize=Q.size();
while (qsize--){
string cur_front=Q.front();
Q.pop();
int size=cur_front.size();
for (int i=0;i<size;i++)
{
char ch=cur_front[i];
for (int j=0;j<26;j++){
cur_front[i]='a'+j;
if (cur_front==end) return res+1;
if (dict.find(cur_front)!=dict.end())
{
Q.push(cur_front);
dict.erase(cur_front);
}
}
cur_front[i]=ch;
}
}
res++;
}
return 0;
}
};
手机扫一扫
移动阅读更方便
你可能感兴趣的文章