Word Ladder

Word Ladder

Description:

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

Notice:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

Example:

Given:
start = “hit”
end = “cog”
dict = [“hot”,”dot”,”dog”,”lot”,”log”]

As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.

分析:

Code:

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
class Solution {
public:
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return an integer
* @date: 2016-9-20
*/
int ladderLength(string start, string end, unordered_set<string> &dict) {
// write your code here
if (start == end) {
return 1;
}
int n = start.size();
if (n < 1 || n != end.size()) {
return 0;
}

queue<string> Q;
Q.push(start);
dict.erase(start);
int length = 2;

while (!Q.empty()) {
int size = Q.size();
for (int i = 0; i < size; i++) {
string word = Q.front(); Q.pop();

for (int i = 0; i < n; i++) {
char oldChar = word[i];

for (char c = 'a'; c <= 'z'; c++) {
if (c == oldChar) continue;

word[i] = c;
if (word == end) {
return length;
}
if (dict.find(word) != dict.end()) {
Q.push(word);
dict.erase(word);
}
}
word[i] = oldChar;
}
}
length++;
}
return 0;
}
};