Word Ladder - LeetCode

題目連接

Word Ladder - LeetCodeblog

注意點

  • 每個變化的字母都要在wordList中

解法

解法一:bfs。相似走迷宮,有26個方向(即26個字母),起點是beginWord,終點是endWord。每一次清空完隊列ret+1表示走了一步。bfs能夠保證是最短路徑。隊列

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> wordSet(wordList.begin(),wordList.end());
        if(!wordSet.count(endWord)) return 0;
        queue<string> q;
        q.push(beginWord);
        int ret = 0;
        while(!q.empty())
        {
            int size = q.size();
            for(int i = 0;i < size;i++)
            {
                string word = q.front();q.pop();
                if(word == endWord) return ret+1;
                for(int j = 0;j < word.size();j++)
                {
                    string newWord = word;
                    for(char ch = 'a';ch <= 'z';ch++)
                    {
                        newWord[j] = ch;
                        if(wordSet.count(newWord) && newWord != word)
                        {
                            q.push(newWord);
                            wordSet.erase(newWord);
                        }
                    }
                }
            }
            ret++;
        }
        return 0;
    }
};

小結

  • 不看別人的解題報告真想不到是迷宮問題
相關文章
相關標籤/搜索