[LeetCode]Word Ladder

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord toendWord, 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.
[LeetCode Source]

思路:这个题目要用到BFS,图论的解法。就是无权最短路径问题。

我们从一个点开始搜索,每次扩展一层,直到找到最后的单词。

我们采用两个队列,一个队列存储距离,另一个队列存储单词。

每次遍历到一个点后要将该点从Dict中删除掉,一种方法是遍历Dict找到相邻的点,

第二种是生成一个单词所有相邻单词然后搜寻。第一种方法会超时。

特别注意对Set操作时,如果采用erase会让原来的迭代器失败。比如:

       for(auto it=wordDict.begin();it!=wordDict.end();++it){
                if(next(now,*it)){
                    dis.push(distance+1);
                    q.push(*it);
                    wordDict.erase(it);
                }
            }
这样编译的确通过,但是会出现运行时错误,原因在于erase之后原来迭代次失效了,导致这个循环出错,一定要避免。
最后AC的代码。这个时间依然有点长还可以改进。

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        queue<string> q;
        q.push(beginWord);
        queue<int> dis;
        dis.push(1);
        wordDict.erase(beginWord);
        while(!q.empty()){
            string now = q.front();
            int distance = dis.front();
            if(now==endWord)
                return distance;
            q.pop();
            dis.pop();
            for(int i=0;i<now.size();++i){
                for(char j='a';j<='z';++j){
                    char rec = now[i];
                    now[i] = j;
                    if(wordDict.find(now)!=wordDict.end())
                    {
                        q.push(now);
                        dis.push(distance+1);
                        wordDict.erase(now);
                    }
                    now[i] = rec;
                }
            }
        }
        return 0;
    }
};


你可能感兴趣的:([LeetCode]Word Ladder)