Skip to content

Commit

Permalink
Create WordLadder-II.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jun 3, 2024
1 parent d1503a6 commit c98469f
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions Graphs/WordLadder-II.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//User function Template for C++

class Solution {
public:
vector<vector<string>> findSequences(string beginWord, string endWord, vector<string>& wordList) {
// code here
set<string>s(wordList.begin(),wordList.end());
queue<vector<string>>q;
q.push({beginWord});
vector<string>usedOnlevel;
usedOnlevel.push_back(beginWord);
int level=0;
vector<vector<string>>ans;
while(!q.empty()){
vector<string>vec=q.front();
q.pop();
// erase all words that has been used in the prev level to transform
if(vec.size()>level){
level++;
for(auto it:usedOnlevel){
s.erase(it);
}
}

string word=vec.back();
if(word==endWord){
if(ans.size()==0){
ans.push_back(vec);
}
else if(ans[0].size()==vec.size()){
ans.push_back(vec);
}
}
for(int i=0;i<word.size();i++){
char ch=word[i];
for(char c='a';c<='z';c++){
word[i]=c;
if(s.count(word)>0){
vec.push_back(word);
q.push(vec);
// mark as visited on the level
usedOnlevel.push_back(word);
vec.pop_back();
}
}
word[i]=ch;

}

}
return ans;


}
};

0 comments on commit c98469f

Please sign in to comment.