Word Ladder解题报告

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.

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.

Link:

https://leetcode.com/problems/word-ladder/#/description

解题方法:

用哈希表把WordList中的单词记下来,然后用bfs。
transform的方法是根据现有单词的每个字母,用26个字母轮流去替换,如果替换出来的结果在哈希表中则代表可以走一步。每走完一步删除哈希表中对应的单词,这样可以保证不会走重复的步骤。

Tips:

用unordered_map在LeetCode里面不能AC,所以需要换成unordered_set。这样占用内存更小。

完整代码:

int ladderLength(string beginWord, string endWord, vector& wordList) 
    {
        unordered_set  hash;
        for(auto a: wordList)
            hash.insert(a);
        queue Q;
        Q.push(beginWord);
        int cnt = 0;
        while(!Q.empty())
        {
            int len = Q.size();
            cnt++;
            for(int i = 0; i < len; i++)
            {
                string curr = Q.front();
                Q.pop();
                if(curr == endWord)
                    return cnt;
                for(int j = 0; j < curr.size(); j++)
                {
                    for(int k = 0; k < 26; k++)
                    {
                        string temp = curr;
                        temp[j] = 'a' + k;
                        if(hash.find(temp) != hash.end())
                        {
                            hash.erase(temp);
                            Q.push(temp);
                        }
                    }
                }
            }
        }
        return 0;
        
    }

你可能感兴趣的:(Word Ladder解题报告)