题目描述
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 transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
思路
先用bfs建图,找到所有路径,记录每个string的parent,然后用dfs搜索路径。
代码
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
set<string> st (wordList.begin(), wordList.end());
if (!st.count(endWord)) return {};
queue<string> que;
que.push(beginWord);
st.erase(beginWord);
st.erase(endWord);
bool found = false;
int l = beginWord.length();
map<string, int> steps;
int step = 1;
steps[beginWord] = 1;
map<string, vector<string> > parent;
while(!que.empty() && !found) {
int size = que.size();
while(size--) {
string cur = que.front();
que.pop();
string p = cur;
for (int i=0; i<l; ++i) {
char ch = p[i];
for (int j='a'; j<='z'; ++j) {
if (p[i] == j) continue;
p[i] = j;
if (p == endWord) {
found = true;
parent[p].push_back(cur);
}else {
if (steps.count(p) && step < steps.at(p)) {
parent[p].push_back(cur);
}
}
if (!st.count(p)) continue;
st.erase(p);
steps[p] = steps[cur] + 1;
parent[p].push_back(cur);
que.push(p);
}
p[i] = ch;
}
}
step++;
}
vector<vector<string>> ans;
vector<string> res;
res.push_back(endWord);
if (found) {
getpath(endWord, beginWord, res, ans, parent);
}
return ans;
}
private:
void getpath(string cur, string beginWord, vector<string>& res, vector<vector<string>>& ans, map<string, vector<string>>& parent) {
if (cur == beginWord) {
ans.push_back(vector<string> (res.rbegin(), res.rend()));
return;
}
for (const auto& p : parent[cur]) {
res.push_back(p);
getpath(p, beginWord, res, ans, parent);
res.pop_back();
}
return;
}
};
第二次写了。。。。。。。
今天玩了半天,奔波了大半天。。。
啥也没干。。。
心累。。。