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.
Have you been asked this question in an interview?
直观反应是图,所有词(包含start和end)组成顶点,“相似”的两个词之间有边,边没有权重。所以这是一个无权无向图。
这道题是求最短路径的,所以使用BFS,code如下:
- int ladderLength(string start, string end, unordered_set<string> &dict) {
- if(0==lookslike(start,end)){
- return 0;
- }
- if(1==lookslike(start,end)){
- return 2;
- }
- dict.erase(start);
- dict.erase(end);
- queue< pair<string,int> > q;
- q.push(make_pair(start, 1));
- unordered_map<string,int>::iterator iter;
- while(!q.empty()){
- pair<string,int> p = q.front();
- q.pop();
- string first=get<0>(p);
- int length=get<1>(p);
- if(1==lookslike(first,end)){
- return length+1;
- }
- else{
- string tmp=first;
- for(int i=0;i<tmp.length();i++){
- for(char c='a';c<='z';c++){
- //tmp[i]=c;
- tmp.replace(i,1,1,c);
- if(dict.find(tmp)!=dict.end()){
- q.push(make_pair(tmp, length+1));
- dict.erase(tmp);
- }
- }
- tmp=first;
- }
- }
- }
- return 0;
- }
- int lookslike(string s1, string s2){
- int diff = 0;
- for (int i = 0; i < s1.length(); i++) {
- if (s1[i] != s2[i]) {
- diff++;
- if (diff >= 2)
- return 2;
- }
- }
- return diff;
- }
相关热门文章
给主人留下些什么吧!~~
评论热议