-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127 Word Ladder.cpp
More file actions
58 lines (55 loc) · 1.8 KB
/
127 Word Ladder.cpp
File metadata and controls
58 lines (55 loc) · 1.8 KB
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
49
50
51
52
53
54
55
56
57
58
static int fastio=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
// https://youtu.be/ZVJ3asMoZ18
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> myset;
bool isPresent = false; //Checks if endWord is present in Dict
//Insert all words from Dict in myset
for(auto word: wordList)
{
if(endWord.compare(word)==0)
isPresent = true;
myset.insert(word); //Insert word in Dict/set
}
if(isPresent==false) //endWord is not present in Dict/set
return 0;
queue<string> q;
q.push(beginWord);
int depth = 0;
while(!q.empty())
{
depth+=1;
int lsize = q.size(); //No of elements at a level
while(lsize--)
{
string curr = q.front();
q.pop();
//check for all possible 1 depth words
for(int i=0;i<curr.length();++i) //For each index
{
string temp = curr;
for(char c='a';c<='z';++c) //Try all possible chars
{
temp[i] = c;
if(curr.compare(temp)==0)
continue; //Skip the same word
if(temp.compare(endWord)==0)
return depth+1; //endWord found
if(myset.find(temp)!=myset.end())
{
q.push(temp);
myset.erase(temp);
}
}
}
}
}
return 0;
}
};