# 单词接龙

字典 wordList 中从单词 beginWord 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" 不在字典中,所以无法进行转换。

 

提示:

## template ```cpp #include using namespace std; class Solution { public: int ladderLength(string beginWord, string endWord, vector &wordList) { unordered_set dict(wordList.begin(), wordList.end()); if (dict.find(endWord) == dict.end()) return 0; queue> q; q.push(make_pair(beginWord, 1)); string tmp; int step; while (!q.empty()) { auto p = q.front(); if (p.first == endWord) return p.second; tmp = p.first; step = p.second; q.pop(); char old_ch; for (int i = 0; i < tmp.size(); ++i) { old_ch = tmp[i]; for (char c = 'a'; c <= 'z'; ++c) { if (c == old_ch) continue; tmp[i] = c; if (dict.find(tmp) != dict.end()) { q.push(make_pair(tmp, step + 1)); dict.erase(tmp); } } tmp[i] = old_ch; } } return 0; } }; ``` ## 答案 ```cpp ``` ## 选项 ### A ```cpp ``` ### B ```cpp ``` ### C ```cpp ```