-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Ladder_II.cpp
More file actions
63 lines (60 loc) · 1.96 KB
/
Word_Ladder_II.cpp
File metadata and controls
63 lines (60 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
bool bfs(const string& start,const string& end,const vector<string>& tmp,unordered_map<string, vector<string>>& children){
unordered_set<string> mapp(tmp.begin(), tmp.end()), current, next;
current.insert(start);
while (true){
for (string word : current)
mapp.erase(word);
for (string word : current){
string parent = word;
for (int i = 0; i < word.size(); i++){
char t = word[i];
for (int j = 0; j < 26; j++){
word[i] = 'a' + j;
if (mapp.find(word) != mapp.end()){
next.insert(word);
children[parent].push_back(word);
}
}
word[i] = t;
}
}
if (next.empty())
return false;
if (next.find(end) != next.end())
return true;
current.clear();
swap(current, next);
}
return false;
}
void dfs(const string& start, const string& end, vector<string>& tmp, vector<vector<string>>& dict, unordered_map<string, vector<string>>& children) {
if (start == end)
dict.push_back(tmp);
else{
for(string word : children[start]){
tmp.push_back(word);
dfs(word, end, tmp, dict, children);
tmp.pop_back();
}
}
}
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, vector<string>& dict) {
vector<vector<string>> res;
unordered_set<string> mapp(dict.begin(), dict.end());
if(mapp.find(end)==mapp.end())
return {};
if(start==end){
res.push_back({start});
return res;
}
unordered_map<string, vector<string>> children;
if (!bfs(start, end, dict, children))
return {};
vector<string> tmp;
tmp.push_back(start);
dfs(start, end, tmp, res, children);
return res;
}
};