/*相当于寻找某个点到另一个点的最短路径,有点想图的最短路径。可以用宽度搜索求解问题,其思路
类似于二叉树的层次遍历,只是在向下走的时候需要从字典中寻找下一层的节点。*/
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
queue<string> q, next;
q.push(beginWord);
int count(1);
while(!q.empty()){
++count;
while(!q.empty()){
string word = q.front();
q.pop();
for(int i = 0; i < word.size(); ++i){
char tmp = word[i];
for(char c = 'a'; c < 'z' + 1; ++c){
if(c != tmp){
word[i] = c;
if(word == endWord) return count;
if(wordDict.find(word) != wordDict.end()){
next.push(word);
wordDict.erase(word);
}
}
}
word[i] = tmp;
}
}
swap(next, q);
}
return 0;
}
};LeetCode之Word Ladder
最新推荐文章于 2019-07-06 22:28:38 发布
本文介绍如何使用宽度优先搜索算法解决从一个单词转换到另一个单词的问题,通过构建单词图来找到最短路径。
2319

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



