相较于单词接龙1,此题主要难点在于记录路径。
BFS适合找最短的深度,但是无法记录路径。
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet(wordList.begin(),wordList.end());
if(wordSet.find(endWord)==wordSet.end()) return 0;
unordered_map<string,int> visitMap;
queue<string> que;
que.push(beginWord);
visitMap.insert(pair<string,int>(beginWord,1));
while(!que.empty()){
string word=que.front();
que.pop();
int path=visitMap[word];
for(int i=0;i<word.size();i++){
string newWord=word;
for(int j=0;j<26;j++){
newWord[i]=j+'a';
if(newWord==endWord) return path+1;
if(wordSet.find(newWord)!=wordSet.end()&&visitMap.find(newWord)==visitMap.end()){
visitMap.insert(pair<string,int>(newWord,path+1));
que.push(newWord);
}
}
}
}
return 0;
}
};
鉴于此采用dfs+bfs的思路
class Solution{
vector<vector<string>> res;
unordered_map<string,vector<string>> neighbor;
public:
vector<vector<string>> findLadders(string beginWord,string endWord,vector<string>& wordList){
unordered_set<string> wordSet(wordList.begin(),wordList.end());
if(wordSet.find(endWord)==wordSet.end()) return res;
unordered_map<string,int> depth;
depth[beginWord]=1;
queue<string> que;
que.push(beginWord);
while(!que.empty()){
string word=que.front();
que.pop();
for(int i=0;i<word.size();i++){
string temp=word;
for(int j=0;j<26;j++){
temp[i]=j+'a';
if(wordSet.count(temp)){
if(depth.count(temp)==0){
que.push(temp);
depth[temp]=depth[word]+1;
neighbor[temp].push_back(word);
}else if(depth[temp]==depth[word]+1){
neighbor[temp].push_back(word);
}
}
}
}
}
vector<string>path;
dfs(beginWord,endWord,path);
return res;
}
void dfs(string& beginWord,string& curr,vector<string> path){
if(curr==beginWord){
path.push_back(curr);
reverse(path.begin(),path.end());
res.push_back(path);
}
path.push_back(curr);
for(auto word:neighbor[curr]) {
dfs(beginWord,word,path);
}
}
};