Word Ladder II 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/word-ladder-ii/description/


Description

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

Given:

beginWord = "hit"

endWord = "cog"

wordList = ["hot","dot","dog","lot","log","cog"]

Return

  1. [
  2. ["hit","hot","dot","dog","cog"],
  3. ["hit","hot","lot","log","cog"]
  4. ]

Note:

  • Return an empty list if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

UPDATE (2017/1/20):

The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

Solution

  1. class Solution {
  2. private:
  3. map<string, int> isVisited;
  4. map<string, vector<string>> preVertex;
  5. public:
  6. bool canTrans(string a, string b) {
  7. int count = 0;
  8. for (int i = 0; i < a.length(); i++)
  9. if (a[i] != b[i]) {
  10. if (count == 0)
  11. count++;
  12. else
  13. return false;
  14. }
  15. return count == 1;
  16. }
  17. vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
  18. vector<vector<string>> resultLists;
  19. vector<string> adjacentWordOfEnd;
  20. if (wordList.size() == 0)
  21. return resultLists;
  22. bool endWordExist = false;
  23. for (auto& w: wordList)
  24. if (w == endWord) {
  25. endWordExist = true;
  26. break;
  27. }
  28. if (!endWordExist)
  29. return resultLists;
  30. isVisited[beginWord] = 0;
  31. queue<string> vq;
  32. vq.push(beginWord);
  33. string qfront;
  34. bool flag = false;
  35. while (!vq.empty()) {
  36. qfront = vq.front();
  37. vq.pop();
  38. if (qfront == endWord)
  39. break;
  40. if (canTrans(qfront, endWord)) {
  41. adjacentWordOfEnd.push_back(qfront);
  42. flag = true;
  43. continue;
  44. }
  45. if (flag)
  46. continue;
  47. int curLevel = isVisited[qfront];
  48. for (auto& w: wordList) {
  49. if (canTrans(qfront, w)) {
  50. if (isVisited.count(w) == 0) {
  51. isVisited[w] = curLevel + 1;
  52. vq.push(w);
  53. preVertex[w].push_back(qfront);
  54. } else if (isVisited[w] == 1 + curLevel) {
  55. preVertex[w].push_back(qfront);
  56. }
  57. }
  58. }
  59. }
  60. if (adjacentWordOfEnd.empty())
  61. return resultLists;
  62. queue< stack<string> > pathQueue;
  63. for (auto& w: adjacentWordOfEnd) {
  64. stack<string> path;
  65. path.push(endWord);
  66. path.push(w);
  67. pathQueue.push(path);
  68. }
  69. while (!pathQueue.empty()) {
  70. stack<string> curPath(pathQueue.front());
  71. pathQueue.pop();
  72. string curVertex = curPath.top();
  73. if (curVertex == beginWord) {
  74. insertPath(resultLists, curPath);
  75. } else if (preVertex[curVertex].size() == 1 && preVertex[curVertex].back() == beginWord) {
  76. curPath.push(beginWord);
  77. insertPath(resultLists, curPath);
  78. } else {
  79. for (int i = 1; i < preVertex[curVertex].size(); i++) {
  80. stack<string> newPath(curPath);
  81. newPath.push(preVertex[curVertex][i]);
  82. pathQueue.push(newPath);
  83. }
  84. curPath.push(preVertex[curVertex][0]);
  85. pathQueue.push(curPath);
  86. }
  87. }
  88. return resultLists;
  89. }
  90. void insertPath(vector<vector<string>>& resultLists, stack<string>& reversePath) {
  91. vector<string> path;
  92. while (!reversePath.empty()) {
  93. path.push_back(reversePath.top());
  94. reversePath.pop();
  95. }
  96. resultLists.push_back(path);
  97. }
  98. };

解题描述

这道题是在leetcode上AC的第一道hard的题,花了一天。一开始想到的还是BFS,在Word Ladder的基础上,多记录下完整的路径。但是实际并没有这么简单。这道题要多考虑相同长度的所有路径的情况。所以我起初想到的解决的办法就是通过记录BFS树中所求路径上每一个点的父节点,然后通过获取endWord的所有父节点来向上回溯直到达到beginWord。但是这里我想少了一点,就是其实路径中间的节点也可以和endWord一样拥有多个父节点。解决了这个问题之后,没有过的测例表明,对于endWord同层节点的排除还没有做。所以就另外加了一个flag来标记以排除与endWord同层的点,这才最终AC。

[Leetcode Week5]Word Ladder II的更多相关文章

  1. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

  2. Java for LeetCode 126 Word Ladder II 【HARD】

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  3. [LeetCode] 126. Word Ladder II 词语阶梯 II

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  4. LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...

  5. [Leetcode Week5]Word Ladder

    Word Ladder题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder/description/ Description Give ...

  6. [LeetCode] 126. Word Ladder II 词语阶梯之二

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  7. [Leetcode][JAVA] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  8. [LeetCode#128]Word Ladder II

    Problem: Given two words (start and end), and a dictionary, find all shortest transformation sequenc ...

  9. leetcode 126. Word Ladder II ----- java

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

随机推荐

  1. Jenkins - 持续集成部署

    1. 安装svn:用于checkout源码 (1)yum 安装:yum -y install subversion (2)查看svn版本信息:svnserver --version 2. 安装jdk ...

  2. 第一篇 Postman的初级使用之设置环境快速切换生成环境与测试环境

    POSTMAN是有谷歌的开源工具,在开发调试.测试执行过程中使用频率非常广泛,本文将记录一些postman在测试中常见的一些配置和使用方法 一.基本的页面区域 略,很简单,大家都会看,再有,学习下面的 ...

  3. final 内部类 static

    [Java中为什么会有final变量]: final这个关键字的含义是“这是无法改变的”或者“终态的”: 那么为什么要阻止改变呢? java语言的发明者可能由于两个目的而阻止改变: 1).效率问题: ...

  4. 学习materialize

    <div class="container"> <div class="row">   </div> <div cla ...

  5. JQuery JTable根据某行的某个值来设置行的背景颜色

    目录 描述 处理方法 参考 描述 某个表的数据是用JQuery的JTable插件进行展示的.现在需求是:当表中的master字段为true时,就将对应的整行的背景颜色设置为浅蓝色. 处理方法 在fie ...

  6. WCF 透明代理

    现在我们通过类似的原理创建一个用于模拟WCF服务端和客户端工作原理的模拟程序.[源代码从这里下载] 目录 一.基本的组件和执行流程 二.创建自定义HttpHandler实现对服务调用请求的处理 三.定 ...

  7. [LOJ#6437][BZOJ5373]「PKUSC2018」PKUSC

    [LOJ#6437][BZOJ5373]「PKUSC2018」PKUSC 试题描述 九条可怜是一个爱玩游戏的女孩子. 最近她在玩一个无双割草类的游戏,平面上有 \(n\) 个敌人,每一个敌人的坐标为 ...

  8. hdu4035 Maze 【期望dp + 数学】

    题目链接 BZOJ4035 题解 神题啊...orz 不过网上题解好难看,数学推导不写\(Latex\)怎么看..[Latex中毒晚期] 我们由题当然能很快写出\(dp\)方程 设\(f[i]\)表示 ...

  9. BZOJ2631 tree(伍一鸣) LCT 秘制标记

    这个题一看就是裸地LCT嘛,但是我wa了好几遍,这秘制标记...... 注意事项:I.*对+有贡献 II.先下传*再下传+(因为我们已经维护了+,不能再让*对+产生贡献)III.维护+用到size # ...

  10. 用JSR的@Inject代替@Autowired完成自动装配

    从spring3.0开始spring支持JSR-330 的标准注解.主要是javax.inject这个包下的: 下面的例子用@Inject代替@Autowired.完成自动装配: MovieFinde ...