题目描述:
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
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
.
寻求path的问题,在我看来dfs和bfs都可以。此题为寻找最短路径,有两种方法:dfs求出所有符合条件的路径,然后取最小值;bfs直接求得的是最短路径之一。此题用dfs会在dict较大时超时,而题目只是要求最短路径,所以bfs为最佳答案。
Mycode (AC = 252ms):
class Solution {
public:
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return an integer
*/
int ladderLength(string start, string end, unordered_set<string> &dict) {
// write your code here
// consider the special case
if (start == end) return 1;
// add start/end into dict, in case dict doesn't contain them
dict.insert(start);
dict.insert(end);
// bfs to search the smallest length
queue<string> str_queue;
queue<int> levels;
str_queue.push(start);
levels.push(1);
while (!str_queue.empty()) {
string crt = str_queue.front();
str_queue.pop();
int level = levels.front();
levels.pop();
vector<string> next_words = getNextWord(crt, dict);
for (int i = 0; i < next_words.size(); i++) {
string word = next_words[i];
if (word == end) {
return level + 1;
}
else {
dict.erase(dict.find(word));
str_queue.push(word);
levels.push(level + 1);
}
}
}
return 0;
}
// get the next word that in the dict
vector<string> getNextWord(string crt, unordered_set<string> &dict) {
vector<string> next_word;
for (int i = 0; i < crt.length(); i++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
string tmp = crt;
tmp[i] = ch;
if (tmp != crt && dict.find(tmp) != dict.end()) {
next_word.push_back(tmp);
}
}
}
return next_word;
}
};