Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord toendWord, 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 length 5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
思路:这个题目要用到BFS,图论的解法。就是无权最短路径问题。
我们从一个点开始搜索,每次扩展一层,直到找到最后的单词。
我们采用两个队列,一个队列存储距离,另一个队列存储单词。
每次遍历到一个点后要将该点从Dict中删除掉,一种方法是遍历Dict找到相邻的点,
第二种是生成一个单词所有相邻单词然后搜寻。第一种方法会超时。
特别注意对Set操作时,如果采用erase会让原来的迭代器失败。比如:
for(auto it=wordDict.begin();it!=wordDict.end();++it){
if(next(now,*it)){
dis.push(distance+1);
q.push(*it);
wordDict.erase(it);
}
}这样编译的确通过,但是会出现运行时错误,原因在于erase之后原来迭代次失效了,导致这个循环出错,一定要避免。
最后AC的代码。这个时间依然有点长还可以改进。
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
queue<string> q;
q.push(beginWord);
queue<int> dis;
dis.push(1);
wordDict.erase(beginWord);
while(!q.empty()){
string now = q.front();
int distance = dis.front();
if(now==endWord)
return distance;
q.pop();
dis.pop();
for(int i=0;i<now.size();++i){
for(char j='a';j<='z';++j){
char rec = now[i];
now[i] = j;
if(wordDict.find(now)!=wordDict.end())
{
q.push(now);
dis.push(distance+1);
wordDict.erase(now);
}
now[i] = rec;
}
}
}
return 0;
}
};
本文介绍了一个经典的图论问题——单词梯。使用BFS算法解决从一个单词转换为另一个单词的问题,要求每次只能改变一个字母,并且中间形成的单词必须在字典中存在。文章详细解析了算法实现过程及注意事项。
2315

被折叠的 条评论
为什么被折叠?



