题解一:
class Solution {
public:
// 求最短转换路径可以使用广度优先搜索
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
vector<int> fg(wordList.size(),0); // 标记每个元素是否已经被访问了
queue<string> wordQ; // 队列用来 广度优先遍历
wordQ.push(beginWord);
int count,result=0; // count用来纪录每一层的个数(用于每一层的扩展)result表示结果(树的层数 深度 就是最短步数))
while(!wordQ.empty()){
count=wordQ.size();// 每一层的个数
result++; // 层数+1
// 用本层节点 扩展下一层 节点
for(int i=0;i<count;i++){
string temp=wordQ.front();
wordQ.pop();
if(temp==endWord){
// 找点目标,返回结果
return result;
}
// 遍历每一个待选择的集合里选取可以扩展的节点加入队列
for(int i=0;i<wordList.size();i++){
if(fg[i]==1) continue; // 这里的fg[i]==0 一定要放到下面的判断的前面,不然超时
if(compare(temp,wordList[i])){
// 扩展
wordQ.push(wordList[i]);
fg[i]=1;
}
}
}
}
return 0;
}
// compare比较两个单词是否只差一个字母,判断是否可以扩展
bool compare(string beginWord,string endWord){
int fg=0;
for(int i=0;i<beginWord.length();i++){
if(beginWord[i]!=endWord[i]){
fg++;
if(fg>1) return false;
}
}
return true;
}
};
双向广度遍历
class Solution {
public:
// 求最短转换路径可以使用广度优先搜索
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
vector<int> fg(wordList.size(),0); // 标记每个元素是否已经被访问了
queue<string> wordQFirst; // 队列用来 广度优先遍历
queue<string> wordQEnd; // 队列用来 广度优先遍历
wordQFirst.push(beginWord);
wordQEnd.push(endWord);
int tt=0;
for(int i=0;i<wordList.size();i++){
if(wordList[i]==endWord){
fg[i]=2;
break;
}
}
if(tt==0) return 0;
int counts,resultFirst=0,resultEnd=0; // counts用来纪录每一层的个数(用于每一层的扩展)result表示结果(树的层数 深度 就是最短步数))
while(!wordQFirst.empty() && !wordQEnd.empty()){
// 前端开始
counts=wordQFirst.size();// 每一层的个数
resultFirst++; // 层数+1
// 用本层节点 扩展下一层 节点
for(int i=0;i<counts;i++){
string temp=wordQFirst.front();
wordQFirst.pop();
if(temp==endWord) return resultFirst;
for(int i=0;i<wordList.size();i++){
if(fg[i]==1) continue;
if(compare(temp,wordList[i])){
// 扩展
if(fg[i]==2) return resultFirst+resultEnd+1;
wordQFirst.push(wordList[i]);
fg[i]=1;
}
}
}
// 后端开始
counts=wordQEnd.size();// 每一层的个数
resultEnd++; // 层数+1
// 用本层节点 扩展下一层 节点
for(int i=0;i<counts;i++){
string temp=wordQEnd.front();
wordQEnd.pop();
for(int i=0;i<wordList.size();i++){
if(fg[i]==2) continue;
if(compare(temp,wordList[i])){
// 扩展
if(fg[i]==1) return resultFirst+resultEnd+1;
wordQEnd.push(wordList[i]);
fg[i]=2;
}
}
}
}
return 0;
}
// compare比较两个单词是否只差一个字母,判断是否可以扩展
bool compare(string beginWord,string endWord){
int fg=0;
for(int i=0;i<beginWord.length();i++){
if(beginWord[i]!=endWord[i]){
fg++;
if(fg>1) return false;
}
}
return true;
}
};