BFS最短路径(十六)127. 单词接龙 困难
127. 单词接龙
字典
wordList中从单词beginWord到endWord的 转换序列 是一个按下述规格形成的序列beginWord -> s1 -> s2 -> ... -> sk:
- 每一对相邻的单词只差一个字母。
- 对于
1 <= i <= k时,每个si都在wordList中。注意,beginWord不需要在wordList中。
sk == endWord给你两个单词
beginWord和endWord和一个字典wordList,返回 从beginWord到endWord的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回0。示例 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 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord、endWord和wordList[i]由小写英文字母组成
beginWord != endWord
wordList中的所有字符串 互不相同
字符串n位,每位有26种变化情况,俩个for循环嵌套,一位一位的进行修改,对修改之后的字符串,判断是否之前访问过(访问过的扔book标记里面),没访问过并且在基因库中的放入队列,并判断是否为目标字符串。
class Solution {
public:
    string change = "abcdefghijklmnopqrstuvwxyz";
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int n = beginWord.size();
        int res = 0;
        set<string> dict(wordList.begin(), wordList.end());
        set<string> book;
        queue<string> q;
        q.push(beginWord);
        book.insert(beginWord);
        res++;
        while(q.size())
        {
            res++;
            int size = q.size();
            while(size--)
            {
                string temp = q.front();
                q.pop();
                for(int i = 0; i < n; i++)
                {
                    char ch = temp[i];
                    for(int j = 0; j < 26; j++)
                    // for(char ch = 'a'; ch <= 'z'; ch++)
                    {
                        temp[i] = change[j];
                        if(dict.find(temp) != dict.end() && book.find(temp) == book.end())
                        {
                            if(temp == endWord)
                                return res;
                            q.push(temp);
                            book.insert(temp);
                        }
                        temp[i] = ch;
                    }
                }
            }
        }
        return 0;
    }
};