Word Ladder II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
class Solution {
public:
//利用BFS构建图,然后利用DFS深度搜索解
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
unordered_set<string> current_step;
unordered_set<string> next_step;
unordered_map<string,unordered_set<string>> Graph;
unordered_set<string> unvisited = wordList;
current_step.insert(beginWord);
unvisited.erase(beginWord);
//每次删除一层的结构,同一层出现可能出现相同解要记住,所以每次只能一层层的删除
while(current_step.count(endWord)==0 && unvisited.size()>0){
for(auto pcu = current_step.begin(); pcu!=current_step.end(); pcu++){
string word = *pcu;
for(int i=0; i<beginWord.length(); ++i)
for(int j=0; j<26; ++j){
string temp = word;
if(temp[i] == 'a'+j)
continue;
temp[i] = 'a'+j;
if(unvisited.count(temp)>0){
next_step.insert(temp);
Graph[word].insert(temp);
}
}
}
if(next_step.empty()) break;
for(auto it = next_step.begin(); it!=next_step.end(); ++it){
unvisited.erase(*it);
}
current_step = next_step;
next_step.clear();
}
vector<vector<string>> ret;
vector<string> path;
DFS(Graph,beginWord,endWord,path,ret);
return ret;
}
void DFS(unordered_map<string,unordered_set<string>> &Graph,string beginWord,string endWord,vector<string> &path,vector<vector<string>> &ret){
path.push_back(beginWord);
if(beginWord == endWord){
//reverse(path.begin(),path.end());
ret.push_back(path);
}
unordered_set<string> adj = Graph[beginWord];
for(auto i=adj.begin(); i!=adj.end(); ++i){
DFS(Graph,*i,endWord,path,ret);
path.pop_back();
}
}
};