题目描述:
字典 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
中的所有字符串 互不相同
题目链接:
. - 力扣(LeetCode)
解题主要思路:
其实这题跟 "最小基因变化" 基本没区别,唯一的区别就是可变化的字母更多了。
"最小基因变化"链接:[LeetCode] 433. 最小基因变化-CSDN博客
解题代码:
class Solution {
public:int ladderLength(string beginWord, string endWord, vector<string>& wordList) {unordered_set<string> hash(wordList.begin(), wordList.end());if (!hash.count(endWord)) return 0;unordered_set<string> vis;queue<string> que;que.push(beginWord);vis.insert(beginWord);int ret = 1;while (que.size()) {++ret;int sz = que.size();while (sz--) {string front = que.front();que.pop();for (int i = 0; i < front.size(); ++i) {string tmp = front;for (char j = 'a'; j <= 'z'; ++j) {tmp[i] = j;if (hash.count(tmp) && !vis.count(tmp)) {if (tmp == endWord) return ret;que.push(tmp);vis.insert(tmp);}}}}}return 0;}
};