要求:跟127题区别是要找所有最短序列
思路:bfs找最短距离,dfs找所有路径
class Solution {
public:
unordered_set<string> S; //对单词列表进行去重
unordered_map<string,int> dist; //记录单词的最短路径
queue<string> q; //bfs用的队列
vector<vector<string> > ans; //存放ans
vector<string> path; //存放单条路径
unordered_map<string, unordered_set<string> > from; //建立字符串之间的有向图
string beginWord; //存放beginwords用于dfs使用,减少参数传递
vector<vector<string>> findLadders(string _beginWord, string endWord, vector<string>& wordList) {
for(const auto& x : wordList)
S.insert(x);
beginWord = _beginWord;
dist[beginWord] = 0;
q.push(beginWord);
while(!q.empty())
{
auto t = q.front(); q.pop();
string r = t;
for(int i = 0; i < t.size(); ++i)
{
t = r;
for(char c = 'a'; c <= 'z'; ++c)
{
t[i] = c;
//如果t存在于S中且是(第一次访问到t或者t的距离等于rd的距离+1),则建立对应的有向图
if(S.count(t) && (dist.count(t) == 0 || dist[t] == dist[r] + 1) )
from[t].insert(r);
bfs第一次遍历到的点一定是最短路径
//如果集合中存在t且是第一次遍历到该点
if(S.count(t) && dist.count(t) == 0)
{
dist[t] = dist[r] + 1;
if(t == endWord)
break;
q.push(t);
}
}
}
}
if(dist.count(endWord) == 0) return ans;
path.emplace_back(endWord);
dfs(endWord);
return ans;
}
void dfs(string t)
{
if(t == beginWord)
{
ans.push_back({path.rbegin(), path.rend()});
return;
}
for(const auto& x : from[t]) //遍历t的源点
{
path.emplace_back(x);
dfs(x);
path.pop_back();
}
}
};