力扣每日一题:单词接龙

给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:

每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:

如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:

输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

输出: 5

解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5。
示例 2:

输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

输出: 0

解释: endWord "cog" 不在字典中,所以无法进行转换。

1.宽度优先搜索
2.之前用的queue<string,pair>来存储每个单词,发现会超时。
3.之后改用unordered_set来替代vector
4.用unordered_map<string ,int>来替代queue<string,pair>存储每个单词以及他们到起始节点的距离。
5.这样就提高了查询的速度 , 就不会超时了 , 运行时长380ms。
6.unordered_set wordset (wordList.begin(),wordList.end()); 将容器或者数组中的元素加到哈希表里。
AC代码:

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;

        unordered_map<string , int> path ;
        path.insert({beginWord,1});

        queue<string> q;
        q.push({beginWord});
        while(!q.empty()){
            string t = q.front();
            q.pop();
            
             for(int i = 0; i < t.size(); i ++){
                string newWord = t;
                for(char c = 'a'; c <= 'z';c ++){
                    newWord[i] = c;
                    if(wordset.count(newWord) && newWord == endWord) return path[t] + 1;
                    if(wordset.count(newWord) && !path.count(newWord)){
                        path[newWord] = path[t] + 1;
                        q.push(newWord);
                    }
                }
             }
        }
        return 0;
    }
};
原文地址:https://www.cnblogs.com/ZhaoHaoFei/p/13933861.html