leetcode 127 单词接龙

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

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

说明:

  • 如果不存在这样的转换序列,返回 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.BFS,从beginword开始,不断遍历与当前单词相差一个字符的单词(已遍历过的不再遍历),直到找到endword。这里最为耗时的操作是判断新的单词是否存在于单词表中,对于它的优化是使用set,set是一个有序的关联容器,查找复杂度为对数级。

解决方案
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        
        std::queue<string> qu;
        qu.push(beginWord);
        std::map<string,int> costInfo;
        costInfo[beginWord] = 1;
        
        set<string> wordSet;
        std::copy( wordList.begin(), wordList.end(), std::inserter( wordSet, wordSet.end() ) );

        
        while(!qu.empty())
        {
            string cur = qu.front();
            qu.pop();
            
            int cost = costInfo[cur];
            for(int i=0;i<cur.size();++i)
            {
                string tmp = cur;
                for(char c = 'a';c <= 'z';++c)
                {
                    if(tmp[i] == c)
                    {
                        continue;
                    }
                    tmp[i] = c;
                    auto it = wordSet.find(tmp);
                    if(it != wordSet.end())
                    {
                        wordSet.erase(it);
                        costInfo[tmp] = cost + 1;
                        qu.push(tmp);
                        
                        if(tmp == endWord)
                        {
                            return cost + 1;
                        }
                    }     
                }
            }
        }
        
        return 0;
    }
};
原文地址:https://www.cnblogs.com/xin-lover/p/9870433.html