字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:
序列中第一个单词是 beginWord 。
序列中最后一个单词是 endWord 。
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典 wordList 中的单词。
给你两个单词 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) 链接:https://leetcode-cn.com/problems/word-ladder
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//这道题目好不容易ac了,一直超时
class Solution {
public:
bool connect(string word1,string word2){//修改了判断两个单词是否只有一个字母不相同的代码 才通过用例
bool f=true;
for(int i=0;i<word1.size();i++){
if(word1[i]!=word2[i]){
if(f){
f=false;
}else{
return false;
}
}
}
return !f;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
wordList.push_back(beginWord);
map<string,vector<string>> graph;//建图
int flag=0;
for(int i=0;i<wordList.size();i++){
if(wordList[i]==endWord){//判断endWord是否在wordList中
flag=1;
}
graph[wordList[i]]=vector<string>();
}
if(flag==0){
return 0;
}
for(int i=0;i<wordList.size();i++){
for(int j=i+1;j<wordList.size();j++){
if(connect(wordList[i],wordList[j])){
graph[wordList[i]].push_back(wordList[j]);
graph[wordList[j]].push_back(wordList[i]);
}
}
}
queue<pair<string,int>> q;
set<string> visit;
q.push(make_pair(endWord,1));
visit.insert(endWord);
while(!q.empty()){//利用bfs进行层次遍历
string node=q.front().first;
int step=q.front().second;
q.pop();
if(node==beginWord){
return step;
}
for(int i=0;i<graph[node].size();i++){
if(visit.find(graph[node][i])==visit.end()){
q.push(make_pair(graph[node][i],step+1));
visit.insert(graph[node][i]);
}
}
}
return 0;
}
};