这道题目较难,转化成图以后,单源无权图最短路径问题,用BFS算法解决。127题只需要输出路径
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet;
for(auto word:wordList){
wordSet.insert(word);
}
if(!wordSet.count(endWord)) return false;
unordered_map<string, int> dist;
queue<string> q;
q.push(beginWord), dist[beginWord] = 1;
while (!q.empty())
{
string tmp = q.front();
q.pop();
if (tmp == endWord) return dist[tmp];
for(int i=0;i<tmp.size();i++){
for(char c='a';c<='z';c++){
string old = tmp;
tmp[i] = c;
if(wordSet.count(tmp)&&dist[tmp]==0){
q.push(tmp);
dist[tmp] = dist[old]+1;
}
tmp = old;
}
}
}
return 0;
}
};
126题需要输出路径,此时需要倒着从终点开始BFS,因为从起点走的不一定是最短路径。
class Solution {
public:
vector<vector<string>> res;
unordered_map<string, int> dist;
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet;
for(auto word:wordList){
wordSet.insert(word);
}
if(!wordSet.count(endWord)) return res;
//unordered_map<string, int> dist;
queue<string> q;
q.push(beginWord), dist[beginWord] = 1;
while (!q.empty())
{
string tmp = q.front();
q.pop();
if (tmp == endWord) break;
for(int i=0;i<tmp.size();i++){
for(char c='a';c<='z';c++){
string old = tmp;
tmp[i] = c;
if(wordSet.count(tmp)&&dist[tmp]==0){
q.push(tmp);
dist[tmp] = dist[old]+1;
}
tmp = old;
}
}
}
vector<string> path;
path.push_back(endWord);
dfs(endWord,path,beginWord);
return res;
}
void dfs(string endWord,vector<string> path,string beginWord){
if(endWord==beginWord){
//ath.push_back(endWord);
reverse(path.begin(),path.end());
res.push_back(path);
return;
}
string tmp = endWord;
for(int i=0;i<endWord.size();i++){
for(char c='a';c<='z';c++){
endWord[i] = c;
if(dist.count(endWord)&&dist[endWord]==dist[tmp]-1){
path.push_back(endWord);
dfs(endWord,path,beginWord);
path.pop_back();
}
endWord = tmp;
}
}
}
};