-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWord Ladder I.cpp
34 lines (31 loc) · 1023 Bytes
/
Word Ladder I.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
/*
Problem Link: https://practice.geeksforgeeks.org/problems/word-ladder/1
*/
class Solution {
public:
int wordLadderLength(string startWord, string targetWord, vector<string>& wordList) {
// Code here
queue<pair<string,int>> q;
q.push({startWord, 1});
unordered_set<string> st(wordList.begin(), wordList.end());
st.erase(startWord);
while(!q.empty()){
string word= q.front().first;
int steps= q.front().second;
q.pop();
if(word == targetWord) return steps;
for(int i=0; i<word.size(); i++){
char initialChar= word[i];
for(char c='a'; c<='z'; c++){
word[i]= c;
if(st.find(word) != st.end()){
st.erase(word);
q.push({word, steps + 1});
}
}
word[i]= initialChar;
}
}
return 0;
}
};