127. Word Ladder (Tree, Queue; WFS)

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

思路:

Step1:把本题看成是树状结构

Step2:通过两个队列,实现层次搜索

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        queue<string> queue_to_push;
        queue<string> queue_to_pop;
        bool endFlag = false;
        string curStr;
        int level = 1;
        char tmp;
        
        queue_to_pop.push(beginWord);
        wordList.erase(beginWord); //if beginWord is in the dict, it should be erased to ensure shortest path
        while(!queue_to_pop.empty()){
            curStr = queue_to_pop.front();
            queue_to_pop.pop();
            
            //find one letter transformation
            for(int i = 0; i < curStr.length(); i++){ //traverse each letter in the word
                for(int j = 'a'; j <= 'z'; j++){ //traverse letters to replace
                    if(curStr[i]==j) continue; //ignore itself
                    tmp = curStr[i];
                    curStr[i]=j;
                    if(curStr == endWord){
                        return level+1;
                    }
                    else if(wordList.count(curStr)>0){ //occur in the dict
                        queue_to_push.push(curStr);
                        wordList.erase(curStr);
                    }
                    curStr[i] = tmp; //back track
                }
            }
            
            if(queue_to_pop.empty()){//move to next level
                swap(queue_to_pop, queue_to_push); 
                level++;
            }
        }
        return 0;
    }
};

 

posted on 2015-10-04 15:21  joannae  阅读(361)  评论(0编辑  收藏  举报

导航