/*相当于寻找某个点到另一个点的最短路径,有点想图的最短路径。可以用宽度搜索求解问题,其思路
类似于二叉树的层次遍历,只是在向下走的时候需要从字典中寻找下一层的节点。*/
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
最新推荐文章于 2020-04-18 01:25:00 发布