Chinaunix首页 | 论坛 | 博客
  • 博客访问: 121087
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-09-22 18:21:15

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

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如下:

  1. int ladderLength(string start, string end, unordered_set<string> &dict) {
  2.         if(0==lookslike(start,end)){
  3.                 return 0;
  4.         }
  5.         if(1==lookslike(start,end)){
  6.                 return 2;
  7.         }
  8.         dict.erase(start);
  9.         dict.erase(end);
  10.         queue< pair<string,int> > q;
  11.         q.push(make_pair(start, 1));
  12.         unordered_map<string,int>::iterator iter;
  13.         while(!q.empty()){
  14.             pair<string,int> p = q.front();
  15.             q.pop();
  16.             string first=get<0>(p);
  17.             int length=get<1>(p);
  18.             if(1==lookslike(first,end)){
  19.                 return length+1;
  20.             }
  21.             else{
  22.                 string tmp=first;
  23.                 for(int i=0;i<tmp.length();i++){
  24.                     for(char c='a';c<='z';c++){
  25.                         //tmp[i]=c;
  26.                         tmp.replace(i,1,1,c);
  27.                         if(dict.find(tmp)!=dict.end()){
  28.                             q.push(make_pair(tmp, length+1));
  29.                             dict.erase(tmp);
  30.                         }
  31.                     }
  32.                     tmp=first;
  33.                 }
  34.             }
  35.         }
  36.         return 0;
  37.     }
  38.     int lookslike(string s1, string s2){
  39.         int diff = 0;
  40.         for (int i = 0; i < s1.length(); i++) {
  41.             if (s1[i] != s2[i]) {
  42.                 diff++;
  43.                 if (diff >= 2)
  44.                     return 2;
  45.             }
  46.         }
  47.         return diff;
  48.     }

阅读(869) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~