赞
踩
给定两个单词(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) { int ans = 0; vector<int> used(wordList.size(), 0); queue<string> que1,que2; string word; que1.push(beginWord); while (!que1.empty() || !que2.empty()) { ans++; while (!que1.empty()) { word = que1.front(); que1.pop(); if (word == endWord) return ans; for (int i = 0; i < wordList.size(); i++) { if (used[i] == 0 && isOnlyOneDifferent(word, wordList[i])) { que2.push(wordList[i]); used[i] = 1; } } } ans++; while (!que2.empty()) { word = que2.front(); que2.pop(); if (word == endWord) return ans; for (int i = 0; i < wordList.size(); i++) { if (used[i] == 0 && isOnlyOneDifferent(word, wordList[i])) { que1.push(wordList[i]); used[i] = 1; } } } } return 0; } bool isOnlyOneDifferent(string s1, string s2) { int sum = 0; for (int i = 0; i < s1.size(); i++) { if (s1[i] != s2[i]) sum++; if (sum > 1) return false; } if (sum == 1) return true; else return false; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。