1. 程式人生 > >Word Ladder - LeetCode

Word Ladder - LeetCode

表示 lee queue 題目 pre nor while leet .cn

目錄

  • 題目鏈接
  • 註意點
  • 解法
  • 小結

題目鏈接

Word Ladder - LeetCode

註意點

  • 每一個變化的字母都要在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;
    }
};

技術分享圖片

小結

  • 不看別人的解題報告真想不到是迷宮問題

Word Ladder - LeetCode