题目描述:
和125一样的题意,每次改变一个字符,中间单词只能是字典里出现过的,要求输出最短路径的所有方案。
思路:
先用bfs建图,保存所有最短路径里的每个结点的父亲结点。
然后用dfs,从最后的单词开始,保存路径。
这里的bfs和之前的不太一样,step在每一层结束以后+1。
代码:
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
set<string> st(wordList.begin(), wordList.end());
map<string, int> step;
if (!st.count(endWord)) return {};
st.erase(beginWord);
st.erase(endWord);
step[beginWord] = 1;
queue<string> que;
que.push(beginWord);
bool found = false;
int stepcnt = 0;
int len = beginWord.length();
map<string, vector<string>> parents;
while(!que.empty() && !found) {
stepcnt++;
for (int size=que.size(); size>0; size--) {
string cur = que.front();
que.pop();
for (int j=0; j<len; ++j) {
string nxt = cur;
char ch = nxt[j];
for (int k=0; k<26; ++k) {
nxt[j] = char('a' + k);
if (ch == nxt[j]) continue;
if (nxt == endWord) {
found = true;
parents[endWord].push_back(cur);
}else if (step.count(nxt) && step[nxt] == stepcnt + 1) {
parents[nxt].push_back(cur);
}
if (st.count(nxt) == 0) continue;
st.erase(nxt);
que.push(nxt);
step[nxt] = step[cur] + 1;
parents[nxt].push_back(cur);
}
}
}
}
vector<vector<string> > ans;
vector<string> path;
path.push_back(endWord);
dfs(endWord, beginWord, parents, path, ans);
return ans;
}
void dfs(const string& endWord, const string& beginWord, map<string, vector<string>>& parents, vector<string>& path, vector<vector<string>>& ans) {
if (endWord == beginWord) {
ans.push_back(vector<string>(path.rbegin(), path.rend()));
return;
}
for (auto nxtWord : parents[endWord]) {
path.push_back(nxtWord);
dfs(nxtWord, beginWord, parents, path, ans);
path.pop_back();
}
}
};
一道题做了一下午。。。for的那里开始居然写 i < que.size(),我一定是失了智。