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 <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.lengthbeginWord、endWord和wordList[i]由小写英文字母组成beginWord != endWordwordList中的所有字符串 互不相同
1 #include2 #include 3 #include 4 #include 5 #include <string> 6 using namespace std; 7 8 class Solution { 9 public: 10 int ladderLength(string beginWord, string endWord, vector<string>& wordList) { 11 if (beginWord.size() != endWord.size()) { 12 return 0; 13 } 14 if (wordList.size() == 0) { 15 return 0; 16 } 17 unordered_set<string> wordSet(wordList.begin(), wordList.end()); // vector转换成set,便于bfs时比较后将相邻元素入栈 18 unordered_set<string> visited; // 已访问单词集 19 queue<string> q; 20 q.push(beginWord); 21 int ans = 1; 22 while (!q.empty()) { 23 unsigned int size = q.size(); 24 for (unsigned int i = 0; i < size; i++) { // 逐层遍历 25 string now = q.front(); 26 q.pop(); 27 for (unsigned int j = 0; j < now.size(); j++) { // 遍历字符位置 28 string next = now; 29 for (unsigned int k = 0; k < 26; k++) { 30 next[j] = k + 'a'; // 替换某个位置字符 31 if (wordSet.count(next) > 0 && visited.count(next) == 0) { 32 if (next == endWord) { 33 return ans + 1; 34 } 35 q.push(next); 36 visited.emplace(next); 37 } 38 } 39 } 40 } 41 ans++; 42 } 43 return 0; 44 } 45 }; 46 47 int main() 48 { 49 vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; 50 string beginWord = "hit"; 51 string endWord = "cog"; 52 Solution *test = new Solution(); 53 cout << test->ladderLength(beginWord, endWord, wordList) << endl; 54 system("pause"); 55 return 0; 56 }