leetcode #127 in cpp

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord toendWord, 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.


Solution:

Since we are to get shortest length, we should perform BFS. In BFS, we scan through current words in queue. For each word, we change one letter and see if new word in in the dictionary. If so we put the new word in queue.  By this we reach the endWord with fewest levels. This gives us the shortest length of change from beginword to e

Code:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        if(beginWord == endWord) {
            
            return 0;
        }
        
        deque<string> next;//BFS traversal 
        next.push_back(beginWord);
        if(wordList.find(beginWord)!=wordList.end()) wordList.erase(beginWord);
        
        int step = 0;
        
        bool isfound = false; 
        while(!next.empty()){
            int cap = next.size(); 
<span style="white-space:pre">	</span>//for current level, collect the next level
            while(cap>0){
                string word = next.front(); 
                next.pop_front();
                if(word == endWord){//if we meet endword, we terminate.
                    return step+1;
                }else{
<span style="white-space:pre">		</span>//change one letter only
                    for(int j = 0; j < word.length(); j ++){
                        char c = word[j];
                        for(int i = 'a'; i <='z'; i++){
                            if(c == i) continue;
                            word[j] = i;
<span style="white-space:pre">			</span>     //after changing one letter, if the new word in in the dictionary, push it into queue
                            if(wordList.find(word)!=wordList.end()){
                                next.push_back(word);
                            }
                        }
                        word[j] = c; 
                    }
                }
                cap--;
            }
<span style="white-space:pre">		</span>//erase the word we have met in the dictionary. This prevents going back and forth like hot -> dot->hot->dot.
            for(int i = 0; i < next.size(); i ++){
                wordList.erase(next[i]);
            }
            if(isfound) break;
            step ++; 
        }
        return 0;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章