Skip to content

Commit

Permalink
Create WordLadder-I.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jun 1, 2024
1 parent 9804f51 commit 50b401d
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Graphs/WordLadder-I.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution {
public:
int ladderLength(string startWord, string targetWord, vector<string>& wordList) {
queue<pair<string,int>>q;
q.push({startWord,1});
unordered_set<string>s(wordList.begin(),wordList.end());
s.erase(startWord);
int ans=0;
while(!q.empty()){
string word=q.front().first;
int freq=q.front().second;
q.pop();
if(word==targetWord){
return freq;
}
// hat initial word
for(int i=0;i<word.size();i++){
char original=word[i];
// aat
// bat
// cat.......... zat
for(char ch='a';ch<='z';ch++){
word[i]=ch;
// it exists in the set
if(s.find(word)!=s.end()){
s.erase(word);
q.push({word,freq+1});
}
}
word[i]=original;
}
}
return 0;
}
};

0 comments on commit 50b401d

Please sign in to comment.