Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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"]

Return

  [
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]

 

Note:

  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

难度挺高的一题。沿用Word Ladder I的思路,此题本质也是图的遍历问题,求的是从给定起点到给定终点之间的所有最短路径。

Word Ladder I 中,找到一条合法路径即返回。然而此题中找到一条之后还需要进行讨论,问题就变复杂了,因为广度优先遍历中之前的节点都已经出队列没法再获取到。

所以,沿用Word Ladder I中的思想,不仅记录每个结点距离start的距离,而且用List记录这个到达这个节点的所有最短路径上的前驱结点。举个例子:

6的List应当为 2 和 3, 因为5 不是最短路径上的点。

这里采用HashMap去处理结点和List的映射关系。

这样在进行广度优先遍历过程中,会有以下几种情况:

1. 相邻结点新结点,那么新结点入队列;建立新结点的List和,把当前结点加入到新结点的List中;记录新结点的最短路径长度为当前结点的最短路径长度L+1

2. 相邻结点在队列中(例如上图结点3出队列时,6还在队列中)且相邻结点的最短路径长度=当前结点最短路径长度+1,那么说明是另一条最短路径,只需要把当前结点加入到相邻结点的List中。

3. 相邻结点在队列中且相邻结点的最短路径长度<当前结点最短路径长度+1,说明这条不是最短路径,那么什么也不做,当前结点默默出队列。

这样我们可以得到从start到end的若干条链,从end开始逆向使用回溯法记录所有的链上的结点即可。

代码如下:

     HashMap<String, ArrayList<String>> nodeSet = new HashMap<String, ArrayList<String>>();
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> re = new ArrayList<List<String>>();
Queue<String> q = new LinkedList<String>();
HashSet<String> hs = new HashSet<String>();
HashMap<String, Integer> dist = new HashMap<String, Integer>();
q.add(start);
nodeSet.put(start, new ArrayList<String>());
nodeSet.put(end, new ArrayList<String>());
dist.put(start, 1); while(!q.isEmpty()) {
String temp = q.poll();
int l = dist.get(temp);
hs.add(temp);
for(int i=0;i<temp.length();i++) {
for(char c='a';c<='z';c++) {
if(temp.charAt(i)==c)
continue;
StringBuilder sb = new StringBuilder(temp);
sb.setCharAt(i,c);
String next = sb.toString();
if(next.equals(end)) {
if(!dist.containsKey(end)) {
dist.put(end,l+1);
nodeSet.get(end).add(temp);
}
else if(dist.get(end)==l+1)
nodeSet.get(end).add(temp);
}
else if(dict.contains(next) && !hs.contains(next)) {
if(!dist.containsKey(next)) {
q.add(next);
dist.put(next, l+1);
ArrayList<String> arr = new ArrayList<String>();
arr.add(temp);
nodeSet.put(next, arr);
} else if(dist.get(next)==l+1)
nodeSet.get(next).add(temp);
}
}
}
}
List<String> path = new ArrayList<String>();
path.add(end);
collect(start,re,path,nodeSet.get(end));
return re;
}
public void collect(String start, List<List<String>> re, List<String> path, ArrayList<String> prevNodes)
{
for(int i=0;i<prevNodes.size();i++)
{
path.add(0,prevNodes.get(i));
if(prevNodes.get(i).equals(start)) {
List<String> pathCopy = new ArrayList<String>(path);
re.add(pathCopy);
}
else
collect(start,re,path,nodeSet.get(prevNodes.get(i)));
path.remove(0);
}
}

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

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

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

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

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

  3. [Leetcode Week5]Word Ladder II

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

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

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

  5. 【leetcode】Word Ladder II

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

  6. [LeetCode#128]Word Ladder II

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

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

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

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

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

  9. Leetcode#126 Word Ladder II

    原题地址 既然是求最短路径,可以考虑动归或广搜.这道题对字典直接进行动归是不现实的,因为字典里的单词非常多.只能选择广搜了. 思路也非常直观,从start或end开始,不断加入所有可到达的单词,直到最 ...

随机推荐

  1. javascript 自调用函数 闭包

    <script type="text/javascript"> var car = {name:"lhs",model:500}; window.o ...

  2. ios base64图片上传失败问题

    今天做图片上传,后台用的是base64解密图片二进制文件,以前都是用表单上传来解决图片上传的,现在后台没有人改,所以研究下base64上传. 需要将图片base64加密,但是调用 [data base ...

  3. <读书笔记>软件调试之道 :实证方法

    有效调试不仅仅是排除缺陷,其包含如下几个步骤 弄明白软件为何运行错误 修复这个问题 避免破坏其它部分 保持或者提高代码的总体质量 确保同样的问题不在其它地方发生,也不会再次发生 构建实验.观察结果 依 ...

  4. c# 文件夾操作

    #region 圖片對應異動           string newFilePath = "~/FileUpLoad/Book/" + bookModel.BookNo;     ...

  5. JDK 环境变量设置

    .net转JAVA了.记心不好,记录一下. 安装好jdk(64位)后找到我的电脑(右键)>属性>高级选项卡>环境变量>,里面有管理员的用户变量,有系统变量.我选的是系统变量.点 ...

  6. 8.10 CSS知识点3

    7.属性选择符 选择符 版本 描述 E[att] CSS2 选择具有att属性的E元素 E[att="val"] CSS2 选择具有att属性值等于val的E元素 E[att~=& ...

  7. 自动获取socket链接状态

    C# TcpClient在连接成功后无法检测连接状态,即使对方关闭了网络连接.以下扩展可检测连接状态: static class TcpClientEx { public static bool Is ...

  8. 线程池pool

    参考链接 http://www.open-open.com/lib/view/open1415453575730.html 参考配置 http://www.cnblogs.com/linjiqin/a ...

  9. meta标签总结

    1."format-detection" format-detection翻译成中文的意思是“格式检测”,顾名思义,它是用来检测html里的一些格式的, 那关于meta的forma ...

  10. Selenium2+python自动化11-定位一组元素find_elements

    前言 前面的几篇都是讲如何定位一个元素,有时候一个页面上有多个对象需要操作,如果一个个去定位的话,比较繁琐,这时候就可以定位一组对象. webdriver 提供了定位一组元素的方法,跟前面八种定位方式 ...