Word Ladder

LeetCode #127


Description:

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:

Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same.

Example:

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Idea:

典型的BFS, 用Queue,为了方便,Queue的每个element用tuple<string, int>存每个word和expand的level。

Code:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {

        tuple<string, int> node;

        unordered_set<string> visited;

        queue<tuple<string, int>> w_queue;

        w_queue.push(make_tuple(beginWord,1));

        while(!w_queue.empty()){
            node=w_queue.front();
            w_queue.pop();

            string word=get<0>(node);
            int level=get<1>(node);

            if(visited.find(word)==visited.end()){ // visit only if not visited
                if(word==endWord) return level; // Found! return

                visited.insert(word); // not visied, visit

                for(auto &e: wordList){
                    // if child is valid, push into queue
                    if(distanceWord(e, word)==1 && visited.find(e)==visited.end()){
                        w_queue.push(make_tuple(e, level+1));
                    }
                }
            }
        }
        return 0;
    }

    // return the number of different characters between two strings
    int distanceWord(string a, string b){
        if(a.size()!=b.size()) return -1;

        int diff=0;
        for(int i=0; i<a.size(); i++){
            if(a[i]!=b[i])
                diff++;
        }
        return diff;
    }
};

results matching ""

    No results matching ""