forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s1.cpp
72 lines (72 loc) · 2.29 KB
/
s1.cpp
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
64
65
66
67
68
69
70
71
72
class Node {
public:
int index;
vector<Node*> next;
Node (int i) {
index = i;
}
};
class Solution {
private:
vector<string> dict;
unordered_map<string, int> m;
vector<vector<string>> ret;
int endIndex;
void dfs(Node *root, vector<string> &path) {
if (root->index == endIndex) {
ret.push_back(path);
return;
}
for (auto node : root->next) {
path.push_back(dict[node->index]);
dfs(node, path);
path.pop_back();
}
}
public:
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
wordList.insert(beginWord);
wordList.insert(endWord);
dict.assign(wordList.begin(), wordList.end());
for (int i = 0; i < dict.size(); ++i) m[dict[i]] = i;
endIndex = m[endWord];
Node *root = new Node(m[beginWord]);
queue<Node*> q;
q.push(root);
bool found = false;
while (!q.empty() && !found) {
int n = q.size();
unordered_map<int, Node*> nextNodes;
while (n--) {
Node *node = q.front();
q.pop();
string s = dict[node->index];
wordList.erase(s);
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
for (char j = 'a'; j <= 'z'; ++j) {
s[i] = j;
if (wordList.find(s) != wordList.end()) {
if (s == endWord) found = true;
Node *next;
int index = m[s];
if (nextNodes.find(index) != nextNodes.end()) {
next = nextNodes[index];
} else {
next = new Node(index);
nextNodes[index] = next;
q.push(next);
}
node->next.push_back(next);
}
}
s[i] = c;
}
}
}
if (!found) return {};
vector<string> path {beginWord};
dfs(root, path);
return ret;
}
};