Word Ladder

时间:2023-03-08 22:34:48

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["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.
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
if(beginWord.size() != endWord.size()) return ; unordered_set<string> visited;
int level = ;
bool found = ;
queue<string> current,next; current.push(beginWord);
while(!current.empty() && !found){
level++;
while(!current.empty() && !found){
string str(current.front());
current.pop();
for(size_t i=;i<str.size();i++){
string new_word(str);
for (char c = 'a';c <= 'z';c++){
if (c == new_word[i]) continue; swap(new_word[i],c);
if(new_word == endWord){
found = ;
break;
} if(wordList.count(new_word) && !visited.count(new_word)){
visited.insert(new_word);
next.push(new_word);
}
swap(new_word[i],c);
}
}
}
swap(current,next);
}
if(found) return level+;
else return ; }
};