-
Notifications
You must be signed in to change notification settings - Fork 3
/
Day-66
59 lines (56 loc) · 2.14 KB
/
Day-66
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
class Solution {
public:
vector<vector<string>> findSequences(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordList1;
for(int i=0; i<wordList.size(); i++)
wordList1.insert(wordList[i]);
vector<vector<string>> ans;
queue<vector<string>> paths;
paths.push({beginWord});
int level = 1;
int minLevel = INT_MAX;
//"visited" records all the visited nodes on this level
//these words will never be visited again after this level
//and should be removed from wordList. This is guaranteed
// by the shortest path.
unordered_set<string> visited;
while (!paths.empty()) {
vector<string> path = paths.front();
paths.pop();
if (path.size() > level) {
//reach a new level
for (string w : visited) wordList1.erase(w);
visited.clear();
if (path.size() > minLevel)
break;
else
level = path.size();
}
string last = path.back();
//find next words in wordList by changing
//each element from 'a' to 'z'
for (int i = 0; i < last.size(); ++i) {
string news = last;
for (char c = 'a'; c <= 'z'; ++c) {
news[i] = c;
if (wordList1.find(news) != wordList1.end()) {
//next word is in wordList
//append this word to path
//path will be reused in the loop
//so copy a new path
vector<string> newpath = path;
newpath.push_back(news);
visited.insert(news);
if (news == endWord) {
minLevel = level;
ans.push_back(newpath);
}
else
paths.push(newpath);
}
}
}
}
return ans;
}
};