-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question71.cpp
33 lines (29 loc) · 1000 Bytes
/
Question71.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
71 -> word ladder
Solution :
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string>s(wordList.begin(),wordList.end());
queue<pair<string,int>>q;
q.push({beginWord,1});
s.erase(beginWord); //as starting it so no point of visited again and agian will make diff in answer
while(!q.empty()){
string word=q.front().first;
int steps=q.front().second;
q.pop();
if(word==endWord)return steps;
for(int i=0;i<word.length();i++){
char original=word[i];
for(char ch='a';ch<='z';ch++){
word[i]=ch;
if(s.find(word)!=s.end()){
s.erase(word);
q.push({word,steps+1});
}
}
word[i]=original;
}
}
return 0;
}
};