Word Ladder I

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

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

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.


BFS is used to search for the word transformation.  To search the next word during transformation, we could build a word relation table for two words with distance as 1.  However, it may take too long to create the word transformation table.


The second idea to implement in word transformation is to search all possible word transformation, and then check if the transformed word is in the dictionary.  For example, if one word's length is 4, it takes 26*4 search to find all possible transformation for this word.


Using the first method, the test could not pass the large test (Maybe I did not use the fastest method to create the word transformation table).  Using the second method, it could pass around 500 ms.

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(dict.find(start) == dict.end() || dict.find(end) == dict.end())
            return 0;
        queue<string> buf[2];
        queue<string> *in = &buf[0], *out = &buf[1];
        unordered_set<string> visited;
        in->push(start);
        visited.insert(start);
        int move = 1;
        while(in->size()){
            move++;
            while(in->size()){
                string word = in->front(); 
                for(int i=0; i<word.length(); i++){
                    word = in->front();
                    for(char c='a'; c<='z'; c++)
                        if(in->front()[i] != c){
                            word[i] = c;
                            if(word == end)
                                return move;
                            if(dict.find(word) == dict.end() || visited.find(word) != visited.end())
                                continue;
                            out->push(word);
                            visited.insert(word);
                        }
                }
                in->pop();
            }
            swap(in, out);
        }
        return 0;
    }
};



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