word-ladder
题目描述
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”,
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.
思想
求路径长度,直接用BFS来做
代码
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start.size()== 0 || end.size() == 0) return 0;
queue<string> Q;
Q.push(start); dict.erase(start);
string temp;
char chTemp;
int count = 1;
int level = 1;
while(!Q.empty()) {
temp = Q.front();
Q.pop(); count--;
for(int i = 0; i < temp.size(); i++) {
chTemp = temp[i];
for(char j = 'a'; j <= 'z'; j++) {
if(temp[i] == j) continue;
temp[i] = j;
if(temp == end) return level+1;
if(dict.count(temp) > 0) {
Q.push(temp);
dict.erase(temp);
}
}
temp[i] = chTemp;
}
if(count == 0) {
count = Q.size();
level++;
}
}
return 0;
}
};