赞
踩
给定两个单词(beginWord 和 endWord)和一个字典,找到从 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" 不在字典中,所以无法进行转换。
C++
- class Solution {
- public:
- int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
- unordered_set<string> word;
- for (auto s : wordList) {
- word.insert(s);
- }
- if (word.find(endWord) == word.end()) {
- return 0;
- }
- queue<string> que;
- que.push(beginWord);
- unordered_set<string> visited;
- visited.insert(beginWord);
- int num = 1;
- while (!que.empty()) {
- int m = que.size();
- for (int i = 0; i < m; i++) {
- string str = que.front();
- que.pop();
- if (str == endWord) {
- return num;
- }
- for (int j = 0; j < str.size(); j++) {
- string ss = str;
- for (int k = 0; k < 26; k++) {
- char c = k + 'a';
- if (c != str[j]) {
- ss[j] = c;
- }
- if (word.find(ss) != word.end() && visited.find(ss) == visited.end()) {
- visited.insert(ss);
- que.push(ss);
- }
- }
- }
- }
- num++;
- }
- return 0;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。