-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
38 lines (37 loc) · 1.03 KB
/
solution.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
class Solution
{
public:
int ladderLength(string start, string end, unordered_set<string> &dict)
{
if(start.size() != end.size()) return 0;
if(start.empty() || end.empty())return 0;
queue<string> path;
path.push(start);
int level = 1;
int count = 1;
dict.erase(start);
while(dict.size() > 0 && !path.empty())
{
string curword = path.front();
path.pop();count--;
for(int i = 0; i < curword.size(); i++)
{
string tmp = curword;
for(char j='a'; j<='z'; j++)
{
if(tmp[i]==j)continue;
tmp[i] = j;
if(tmp==end)return level+1;
if(dict.find(tmp) != dict.end()) path.push(tmp);
dict.erase(tmp);
}
}
if(count==0)
{
count = path.size();
level++;
}
}
return 0;
}
};