-
Notifications
You must be signed in to change notification settings - Fork 0
/
Word Ladder II.cpp
55 lines (48 loc) · 1.67 KB
/
Word Ladder II.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
/*
Problem Link: https://practice.geeksforgeeks.org/problems/word-ladder-ii/1
*/
class Solution {
public:
vector<vector<string>> findSequences(string beginWord, string endWord, vector<string>& wordList) {
// code here (Very Tough Problem to implement)
queue<vector<string>> q;
q.push({beginWord});
unordered_set<string> st(wordList.begin(), wordList.end());
vector<string> usedForLevel;
usedForLevel.push_back(beginWord);
int level= 0;
vector<vector<string>> ans;
while(!q.empty()){
vector<string> vec= q.front();
q.pop();
if(vec.size() > level){
level++;
for(auto it: usedForLevel){
st.erase(it);
}
usedForLevel.clear();
}
string word= vec.back();
if(word == endWord){
if( (ans.size() == 0) || (ans[0].size() == vec.size()) ){
ans.push_back(vec);
}
}
for(int i=0; i<word.size(); i++){
char inititalCh= word[i];
for(char c='a'; c<='z'; c++){
word[i]= c;
if(st.count(word) > 0){
vec.push_back(word);
q.push(vec);
// mark as visited
usedForLevel.push_back(word);
vec.pop_back();
}
}
word[i]= inititalCh;
}
} // queue becomes empty
return ans;
}
};