思路:
因为求的是最短路径,所以理所当然使用bfs,从 beginWord 开始,每次列举这个单词能变换的所有情况,如果在 wordList 中,就放入队列里继续进行 bfs,每次维护一个 path 用来记录变换成这个单词变换的次数。难度还是比较适中的
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> word(wordList.begin(),wordList.end());
if(word.count(endWord)==0){
return 0;
}
unordered_map<string,int> path;//记录到这个单词的路径长度
queue<string> q;
q.push(beginWord);
path[beginWord]=1;
while(!q.empty()){
string cur=q.front();
q.pop();
for(int i=0;i<cur.length();i++){
int Path=path[cur];
for(int k=0;k<26;k++){//列举每一个变换的可能
string tmp=cur;
tmp[i]='a'+k;
if(tmp==endWord)return Path+1;
if(word.count(tmp)==1 && path.count(tmp)==0){//在单词集合中存在且没有被加入过
path[tmp]=Path+1;
q.push(tmp);
}
}
}
}
return 0;
}
};