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. noip2008解题报告

    T1.笨小猴 给出一个单词求出现次数最多和最少之差是不是质数. 很水的.统计一下反正就26个字母. T2.火柴棒等式 给出火柴棒数,求形如 a+b=c能拼成的等式个数. 先减去4根(+,=),然后枚举 ...

  2. PAT 1001. 害死人不偿命的(3n+1)猜想 (15)

    卡拉兹(Callatz)猜想: 对任何一个自然数n,如果它是偶数,那么把它砍掉一半:如果它是奇数,那么把(3n+1)砍掉一半.这样一直反复砍下去,最后一定在某一步得到 n=1.卡拉兹在1950年的世界 ...

  3. Hue整合Sqoop报空指针异常的解决方法

    hue是一个Apache基金会下的一个开源图形化管理工具,使用python语言开发,使用的框架是Django.而sqoop也是Apache的一个开源工具,是使用Java语言开发,主要用于进行hdfs和 ...

  4. maven自动部署到远程tomcat教程

    使用maven的自动部署功能可以很方便的将maven工程自动部署到远程tomcat服务器,节省了大量时间. 本文章适用于tomcat的7.x ,8.x, 9.x版本. 下面是自动部的步骤 1,首先,配 ...

  5. sqoop job 踩过的坑

    sqoop 执行可以以job形式 也可以执行用命令执行,再用sqoopjob时,踩了几个坑,分享一下 1.服务器重启 由于服务器增加硬盘,需要重启后,发现sqoop job 无法执行,报连接数据库IO ...

  6. [ 学习路线 ] 2015 前端(JS)工程师必知必会 (2)

    http://segmentfault.com/a/1190000002678515?utm_source=Weibo&utm_medium=shareLink&utm_campaig ...

  7. HTML <!DOCTYPE> Declaration

    <!DOCTYPE html><html><head><title>Title of the document</title></he ...

  8. [2015hdu多校联赛补题]hdu5303 Delicious Apples

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5303 题意:在一个长为L的环形路径上种着一些苹果树,告诉你苹果树的位置(题目中以0~L指示坐标)及苹果 ...

  9. [2015hdu多校联赛补题]hdu5324 Boring Class

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5324 题意:给你一个二维的序列,让你找出最长的第一维升第二维降的子序列(如果多个答案,输出字典序最小) ...

  10. 如何使用本地yum源?

    首先为大家介绍在Centos系统上如何利用系统光盘/镜像作为yum源,实现程序包的安装等操作 1.首先在VM虚拟机上确保已载入光盘镜像,载入成功后显示如下效果. 2.挂载光盘镜像文件,使用命令: mo ...