Word Ladder

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 0;
        
        unordered_set<string> visited;
        int level = 0;
        bool found = 0;
        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=0;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 = 1;
                            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+1;
        else return 0;
        
    }
};
原文地址:https://www.cnblogs.com/wxquare/p/5906160.html