【LeetCode】127. Word Ladder


Word Ladder

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.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

 

最短搜索路徑,所以是廣度優先搜索(BFS)。

有幾個問題需要注意:

1、怎樣判斷是否為鄰居節點?

按照定義,存在一個字母差異的單詞為鄰居,因此采用逐位替換字母並查找字典的方法尋找鄰居。

(逐個比對字典里單詞也可以做,但是在這題的情況下,時間復雜度會變高,容易TLE)

2、怎樣記錄路徑長度?

對隊列中的每個單詞記錄路徑長度。從start進入隊列記作1.

長度為i的字母的鄰居,如果沒有訪問過,則路徑長度為i+1

struct Node
{
    string word;
    int len;
    
    Node(string w, int l): word(w), len(l) {}
};

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        queue<Node*> q;
        unordered_map<string, bool> m;
        Node* beginNode = new Node(beginWord, 1);
        q.push(beginNode);
        m[beginWord] = true;
        while(!q.empty())
        {
            Node* frontNode = q.front();
            q.pop();
            string frontWord = frontNode->word;
            //neighbor search
            for(int i = 0; i < frontWord.size(); i ++)
            {
                for(char c = 'a'; c <= 'z'; c ++)
                {
                    if(c == frontWord[i])
                        continue;
                        
                    string frontWordCp = frontWord;
                    frontWordCp[i] = c;
                    //end
                    if(frontWordCp == endWord)
                        return frontNode->len+1;
                    if(wordDict.find(frontWordCp) != wordDict.end() && m[frontWordCp] == false)
                    {
                        Node* neighborNode = new Node(frontWordCp, frontNode->len+1);
                        q.push(neighborNode);
                        m[frontWordCp] = true;
                    }
                }
            }
        }
        return 0;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM