-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathword_lad_1.cpp
39 lines (33 loc) · 1.11 KB
/
word_lad_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
class Solution {
public:
int wordLadderLength(string startWord, string targetWord, vector<string>& wordList) {
// Code here
queue<pair<string, int>> q; // word, level
q.push({startWord, 1});
unordered_set<string> st(wordList.begin(), wordList.end());
st.erase(startWord); // marking start as visited
while(!q.empty())
{
string word = q.front().first;
int level = q.front().second;
q.pop();
if(word == targetWord)
return level;
for(int i = 0; i < word.size(); i++) // h,a,t
{
char og = word[i];
for(char it = 'a'; it <= 'z'; it++) // ha, hb, hz..aa,ab,ac..
{
word[i] = it;
if(st.find(word) != st.end())
{
st.erase(word);
q.push({word, level+1});
}
}
word[i] = og;
}
}
return 0;
}
};