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 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和Dijkstra,其区别在于BFS不能用于带权重图,而Dijkstra可以。另外,BFS和Dijkstra的区别是前者的时间复杂度是O(n),后者最多优化到O(mlogn),如果条件成立一般选择BFS。本题中,两字符串之间是无权重的,连通是1,不连通是无穷,故本题采用BFS方法。

首先,要进行图的映射,顶点是每个字符串,若是两个字符串相差1个字符且后者在dict中,就相连构成边;然后,将起点加入到队列中,遍历和其相差为1的字符串,将其加入到队列中,直到找到目标字符串(找不到就返回0)。这里值得注意的是:寻找和某一个字符相差1的字符串的方式,不是遍历字典中的每一个字符串,这样当字典中元素较多时,将会耗时严重。这次采用,对该字符串的每个位置上的字符,用26个字母进行替换,找到和其相差为1的所有字符串;还有一点值得注意的是,每次在字典中找到某一个字符串以后,要在字典中删除该字符串,这样可以避免重复查找(详细说明见这里)。以题中的例子为例,见下图:

如上图,每一层依次加入到队列中,只要先找到目标词语,就返回此时的值就行。参考了这里,代码如下:

 class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict)
{
queue<pair<string,int>> que;
que.push(make_pair(start,));
dict.erase(dict.find(start)); while( !que.empty())
{
auto val=que.front();
que.pop();
if(val.first==end) return val.second; for(int i=;i<val.first.size();++i)
{
string str=val.first;
for(int j=;j<;++j)
{
str[i]='a'+j;
if(dict.find(str) !=dict.end())
{
que.push(make_pair(str,val.second+));
dict.erase(str);
}
}
}
}
return ;
}
};

思路是一样的,换一种写法;

 class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict)
{
unordered_map<string,int> m;
queue<string> que;
m[start]=;
que.push(start); while( !que.empty())
{
string val=que.front();
que.pop(); for(int i=;i<val.size();++i)
{
string str=val;
for(int j=;j<;++j)
{
str[i]='a'+j;
if(dict.count(str)&&str==end)
return m[val]+;
if(dict.count(str)&& !m.count(str))
{
que.push(str);
m[str]=m[val]+;
}
}
}
}
return ;
}
};

最新文章

  1. table 边框显示
  2. c#中如何不通过后台直接用js筛选gridview中的数据条件筛选查询?
  3. 完成端口(CompletionPort)详解
  4. 8款超酷而实用的CSS3按钮动画
  5. 实用项目管理前台框架:EasyUI,ExtJs
  6. Tomcat: IllegalStateException: No output folder --reference
  7. HTML5 Web缓存&amp;运用程序缓存&amp;cookie,session
  8. Spring Boot实战笔记(二)-- Spring常用配置(Scope、Spring EL和资源调用)
  9. [date] 时间问题: 更新时间距离现在3个月
  10. 如何将web项目部署到weblogic
  11. Mac安装minikube
  12. CTime格式化
  13. VS Code折腾记 - (2) 快捷键大全,没有更全
  14. 我眼中的Linux系统和红帽RHCE认证
  15. 【java规则引擎】《Drools7.0.0.Final规则引擎教程》第4章 4.2 agenda-group
  16. Kafka 接受数据并消费到hbase数据库
  17. vi的一些使用技巧
  18. 【JavaScript】富文本编辑器
  19. usermod命令、用户密码管理、mkpasswd命令
  20. iOS 阶段学习第三天笔记(运算符)

热门文章

  1. jQuery 打气球小游戏 点击气球爆炸效果
  2. __name__ 和 &quot;__main__&quot;
  3. MySQL的边角料
  4. 洛谷U32670 小凯的数字(比赛)
  5. DHT11温湿度传感器编程思路以及代码的实现(转载)
  6. 学习RUNOOB.COM进度二
  7. ABS(引数と同じ大きさの正の数を返す)
  8. spfa专题
  9. 对C语言连等式的学习
  10. guacamole实现剪切复制