-
Notifications
You must be signed in to change notification settings - Fork 0
/
127-Word Ladder (BFS).cpp
54 lines (54 loc) · 1.48 KB
/
127-Word Ladder (BFS).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
49
50
51
52
53
54
class Solution {
public:
unordered_set<string> dict;
queue<string> q;
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
char letter;
dict.reserve(wordList.size());
for(string &i:wordList)
dict.insert(i);
for(int i=0;i<beginWord.length();i++)
{
letter=beginWord[i];
for(int j=0;j<26;j++)
{
beginWord[i]='a'+j;
if(dict.find(beginWord)!=dict.end())
{
q.push(beginWord);
dict.erase(beginWord);
}
}
beginWord[i]=letter;
}
int dist=2;
int size;
while(!q.empty())
{
size=q.size();
for(int k=0;k<size;k++)
{
if(q.front()==endWord)
return dist;
for(int i=0;i<q.front().length();i++)
{
letter=q.front()[i];
for(int j=0;j<26;j++)
{
q.front()[i]='a'+j;
if(dict.find(q.front())!=dict.end())
{
q.push(q.front());
dict.erase(q.front());
}
}
q.front()[i]=letter;
}
q.pop();
}
dist++;
}
return 0;
}
};