-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127. Word Ladder.cpp
More file actions
47 lines (44 loc) · 1.78 KB
/
127. Word Ladder.cpp
File metadata and controls
47 lines (44 loc) · 1.78 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
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string>& dict) //use graph's BFS
{
if (start.size() != end.size())
return 0;
if (start.empty() || end.empty())
return 1;
if (dict.size() == 0)
return 0;
int distance = 1; //!!!
queue<string> queToPush, queToPop;
queToPop.push(start);
while (dict.size() > 0 && !queToPop.empty())
{
while (!queToPop.empty())
{
string str(queToPop.front()); //!!!how to initialize the str
queToPop.pop(); //!!! should pop after it is used up
for (int i = 0; i < str.size(); i++)
{
for (char j = 'a'; j <= 'z'; j++)
{
if (j == str[i])
continue;
char temp = str[i];
str[i] = j;
if (str == end)
return distance + 1; //found it
if (dict.count(str) > 0) //exists in dict
{
queToPush.push(str); //find all the element that is one edit away
dict.erase(str); //delete corresponding element in dict in case of loop
}
str[i] = temp; //
}
}
}
swap(queToPush, queToPop); //!!! how to use swap
distance++;
} //end while
return 0; //all the dict words are used up and we do not find dest word
}
};