-
Notifications
You must be signed in to change notification settings - Fork 9
/
12. Word Ladded 1.cpp
48 lines (42 loc) · 1.34 KB
/
12. Word Ladded 1.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
// Problem link - https://bit.ly/48pveY2
class Solution {
public:
int wordLadderLength(string startWord, string targetWord, vector<string>& wordList) {
// Code here
if(startWord==targetWord) return 0;
unordered_set<string> st(wordList.begin(), wordList.end()), vis;
if(st.find(targetWord)==st.end()) return 0;
queue<string> q;
q.push(startWord);
vis.insert(startWord);
int ans=1;
while(!q.empty()) {
int s=q.size();
while(s--){
startWord=q.front();
q.pop();
if(startWord==targetWord) return ans;
for(auto &c: startWord){
auto temp=c;
for(int i=0;i<26;i++){
c='a'+i;
if(vis.find(startWord)==vis.end() && st.find(startWord)!=st.end()){
q.push(startWord);
vis.insert(startWord);
}
}
c=temp;
}
}
ans++;
}
return 0;
}
};
/*
Time complexity: O(n*m)
Space complexity: O(n*m)
*/
// Code by Shumbul Arifa - https://linktr.ee/shumbul
// Follow 21 days DSA Challenge - www.shumbularifa.com
// Video solutions available on my YouTube