链接:
https://leetcode-cn.com/problems/word-ladder/
描述:
示例:
代码:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordDirt(wordList.begin(),wordList.end());
unordered_set<string> visted;
visted.insert(beginWord);
queue<string> q;
q.push(beginWord);
int res = 1;
while(!q.empty())
{
int nextsize = q.size();
while(nextsize--)
{
string curWord =q.front();
q.pop();
for(int i = 0;i<curWord.size();i++)
{
string newWord = curWord;
for(auto ch = 'a';ch<='z';ch++)
{
newWord[i] = ch;
if(!wordDirt.count(newWord) || visted.count(newWord)) continue;
if(newWord == endWord) return res+1;
visted.insert(newWord);
q.push(newWord);
}
}
}
res++;
}
return 0;
}
};
|