leetcode127.单词接龙
本题的思路就是将所有可转换的序列相连,构成图,然后选择起始词作为广度优先遍历的起点,那么就能找到转换的最小步骤数
而这里的两个单词是否相连不是真的把他们弄成一张图,而是采用暴力枚举,逐个尝试替换字母,然后判断替换后的单词是否在原来的字典中,如果在,那么二者就是相连的
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
//将单词列表转化为哈希表
unordered_set<string> wordSet(wordList.begin(),wordList.end());
//用来判断单词是否已经访问过,并且记录转换到当前单词需要的步数
unordered_map<string,int> visitedMap;
queue<string> que;
que.push(beginWord);
visitedMap.insert(pair<string,int>(beginWord,1));
while(!que.empty()){
string currentWord=que.front();
que.pop();
int step=visitedMap[currentWord];
for(int i=0;i<currentWord.size();i++){
string newWord=currentWord;
for(int j=0;j<26;j++){
newWord[i]='a'+j;
//找到结果单词且结果单词在字典中直接把步骤数目返回
if(endWord==newWord&&wordSet.find(newWord)!=wordSet.end())
return step+1;
//如果替换得到的单词存在于字典中并且从来没有访问过
else if(wordSet.find(newWord)!=wordSet.end()&&visitedMap.find(newWord)==visitedMap.end()){
que.push(newWord);
visitedMap.insert(pair<string,int>(newWord,step+1));
}
}
}
}
//不能转换到endWord,返回0
return 0;
}
};