LeetCode-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",
return its length 5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
将每差一个字母的两个字符串连起来可以构成图,找图上给定起点终点的最短距离,用BFS
注意unordered_set,map, queue的使用
class Solution {
public:
int ladderLength(string start, string end, std::unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
queue<string> q;
map<string,int> m;
q.push(start);
m[start]=0;
while(q.size()!=0){
string top=q.front();
q.pop();
string s=top;
for(int i=0;i<top.length();i++){
char c=top[i];
for(int j='a';j<c;j++){
s[i]=j;
if(s==end)return m[top]+2;
if(dict.find(s)!=dict.end()&&m.find(s)==m.end()){
m[s]=m[top]+1;
q.push(s);
}
}
for(int j=c+1;j<'z';j++){
s[i]=j;
if(s==end)return m[top]+2;
if(dict.find(s)!=dict.end()&&m.find(s)==m.end()){
m[s]=m[top]+1;
q.push(s);
}
}
s[i]=c;
}
}
return 0;
}
};
浙公网安备 33010602011771号