class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string>string_set(wordList.begin(),wordList.end());
if(!string_set.count(endWord))return 0;
unordered_map<string,int>string_map{{beginWord,1}};
queue<string>q{{beginWord}};
while(!q.empty()){
string word=q.front();
q.pop();
for(int i=0;i<word.length();++i){
string new_word=word;
for(char ch='a';ch<='z';++ch){
new_word[i]=ch;
if(string_set.count(new_word)&&new_word==endWord)return string_map[word]+1;
if(string_set.count(new_word)&&!string_map.count(new_word)){
q.push(new_word);
string_map[new_word]=string_map[word]+1;
}
}
}
}
return 0;
}
};
127. Word Ladder
最新推荐文章于 2021-10-31 08:20:30 发布