forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
126_Word_Ladder_2
60 lines (52 loc) · 1.91 KB
/
126_Word_Ladder_2
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
Leetcode 126 : Word Ladder II
Detailed video explanation : https://youtu.be/ZkmKsxls0Rs
=========================================================
C++:
----
class Solution {
vector<string> findNeighbors(string word, unordered_set<string>& wordList){
vector<string> neighbors;
for(int i = 0; i < word.size(); ++i){
int s = word[i];
for(char c = 'a'; c <= 'z'; ++c){
word[i] = c;
if(wordList.find(word) != wordList.end())
neighbors.push_back(word);
}
word[i] = s;
}
return neighbors;
}
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> word_list(wordList.begin(), wordList.end());
vector<vector<string>> result;
queue<vector<string>> Q;
Q.push({beginWord});
bool reached_end = false;
unordered_set<string> visited;
while(!Q.empty()){
int n = Q.size();
for(int i = 0; i < n; ++i){
vector<string> path = Q.front(); // running path
Q.pop();
vector<string> neighbors = findNeighbors(path.back(), word_list);
for(int j = 0; j < neighbors.size(); ++j){
vector<string> new_path(path.begin(), path.end());
new_path.push_back(neighbors[j]);
visited.insert(neighbors[j]);
Q.push(new_path);
if(neighbors[j] == endWord){
result.push_back(new_path);
reached_end = true;
}
}
}
if(reached_end) break;
for(auto it = visited.begin(); it != visited.end(); ++it)
word_list.erase(*it);
visited.clear();
}
return result;
}
};