题目描述
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- -------------------------------------------------------------------------------
- 思路:借助队列实现树的广度遍历。
1
class Solution {
2
public:
3
int ladderLength(string start, string end, unordered_set<string> &dict) {
4
if (start == end)
5
return 1;
6
queue<string> que;
7
que.push(start);
8
int pre_size = 1;//上一层宽度
9
int len = 1;//层高
10
while (!que.empty()){
11
int cur_size = 0;//当前层宽度
12
for (int i=0; i<pre_size; ++i){
13
string str = que.front();
14
que.pop();
15
for (int j=0; j<str.size(); ++j){
16
char old = str[j];
17
for (char c='a'; c<='z'; ++c){
18
if (c == old)
19
continue;
20
str[j] = c;
21
if (str == end)
22
return len+1;
23
if (dict.find(str) != dict.end()){
24
que.push(str);
25
dict.erase(str);
26
++cur_size;
27
}
28
}
29
str[j] = old;
30
}
31
}
32
pre_size = cur_size;
33
++len;
34
}
35
return 0;
36
}
37
};
您的代码已保存