【题目描述】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.
【解题思路】这种题,肯定是每次改变单词的一个字母,然后逐渐搜索,很多人一开始就想到用dfs,其实像这种求最短路径、树最小深度问题bfs最适合,可以参考我的这篇博客bfs(层序遍历)求二叉树的最小深度。本题bfs要注意的问题:
和当前单词相邻的单词是:对当前单词改变一个字母且在字典中存在的单词
找到一个单词的相邻单词,加入bfs队列后,要从字典中删除,因为不删除的话会造成类似于hog->hot->hog的死循环。而删除对求最短路径没有影响,因为我们第一次找到该单词肯定是最短路径,即使后面其他单词也可能转化得到它,路径肯定不会比当前的路径短(如果要输出所有最短路径,则不能立即从字典中删除,具体见下一题)
bfs队列中用NULL来标识层与层的间隔,每次碰到层的结尾,遍历深度+1
【考查内容】数组,查找,宽度搜索
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
//BFS遍历找到的第一个匹配就是最短转换,空字符串是层与层之间的分隔标志
queue<string> Q;
Q.push(start); Q.push("");
int res = 1;
while(Q.empty() == false){
string str = Q.front();
Q.pop();
if(str != ""){
int strLen = str.length();
for(int i = 0; i < strLen; i++){
char tmp = str[i];
for(char c = 'a'; c <= 'z'; c++){
if(c == tmp)
continue;
str[i] = c;
if(str == end)
return res+1;
if(dict.find(str) != dict.end()){
Q.push(str);
dict.erase(str);
}
}
str[i] = tmp;
}
}
else if(Q.empty() == false){//到达当前层的结尾,并且不是最后一层的结尾
res++;
Q.push("");
}
}
return 0;
}
};