import java.util.*;

/**
* Source : https://oj.leetcode.com/problems/word-ladder-ii/
*
*
* Given two words (start and end), and a dictionary, find all shortest transformation
* sequence(s) from start to end, such that:
*
* Only one letter can be changed at a time
* 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.
*
*/
public class WordLadder2 { /**
* 在wordladder1的基础上,找到start到end的所有变化路径
*
* 这里需要回溯,采用深度优先DFS
*
* 优化:
* 因为这需要回溯,也就是说可能会重复计算某个单词的neighbors,所以可以实现将所有的单词构造成一棵树,就不需要每次计算neighbors
*
* @param start
* @param end
* @param dict
* @return
*/
public List<List<String>> findLadders (String start, String end, String[] dict) {
Set<String> set = new HashSet<String>(Arrays.asList(dict));
set.add(end);
List<List<String>> result = new ArrayList<List<String>>();
Set<String> list = new HashSet<String>();
list.add(start);
List<String> ladder = new ArrayList<String>(); recursion(list, end, ladder, result, set);
return result;
} public void recursion (Set<String> list, String end, List<String> ladder, List<List<String>> result, Set<String> set) {
for (String str : list) {
ladder.add(str);
if (str.equals(end)) {
result.add(new ArrayList<String>(ladder));
}
Set<String> neighbors = findNeighbors(str,set);
recursion(neighbors, end, ladder, result, set);
set.addAll(neighbors);
ladder.remove(str);
}
} private Set<String> findNeighbors (String cur, Set<String> dict) {
Set<String> neighbors = new HashSet<String>();
for (int i = 0; i < cur.length(); i++) {
for (int j = 0; j < 26; j++) {
char ch = (char) ('a' + j);
if (cur.charAt(i) != ch) {
String candidate = "";
if (i == cur.length()-1) {
candidate = cur.substring(0, i) + ch;
} else {
candidate = cur.substring(0, i) + ch + cur.substring(i+1);
}
if (dict.contains(candidate)) {
neighbors.add(candidate);
dict.remove(candidate);
}
}
}
}
return neighbors;
} public static void print (List<List<String>> list) {
for (List<String> strList : list) {
System.out.println(Arrays.toString(strList.toArray(new String[strList.size()])));
}
} public static void main(String[] args) {
WordLadder2 wordLadder2 = new WordLadder2();
String start = "hit";
String end = "cog";
String[] dict = new String[]{"hot","dot","dog","lot","log"};
print(wordLadder2.findLadders(start, end, dict));
}
}

leetcode — word-ladder-ii的更多相关文章

  1. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  2. LeetCode :Word Ladder II My Solution

    Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start  ...

  3. LeetCode: Word Ladder II 解题报告

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

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

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

  5. LeetCode: Word Ladder II [127]

    [题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  6. [LeetCode] Word Ladder II

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

  7. leetcode—word ladder II

    1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...

  8. LeetCode:Word Ladder I II

    其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...

  9. [Leetcode Week5]Word Ladder II

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

  10. 【leetcode】Word Ladder II

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

随机推荐

  1. Machine Learning学习资源

    引申:非原创,转载来自:https://blog.csdn.net/ptkin/article/details/50995140

  2. #工具 Intellij IDEA中自定义的Maven Archetype管理

    背景,手贱在输入自定义的 archetype时后面多输入了一个空格 解决:自定义的Archetype 会保存在Windows下面的文件中 C:\Users\<user>\.IntelliJ ...

  3. SPA 单页面应用程序。

    看到这个问题,先说下自己的理解到的程度,再去参考做修正,争取这一次弄懂搞清楚 自己的理解: 单页面应用程序,解决浏览器获取数据刷新页面的尴尬,通过ajax请求获取数据达到异步更新视图的按钮,原理的实现 ...

  4. group by 多个字段

    众所周知,group by 一个字段是根据这个字段进行分组,那么group by 多个字段的结果是什么呢?由前面的结论类比可以得到,group by 后跟多个子段就是根据多个字段进行分组 注:下面的例 ...

  5. SpringMvc 中的实用工具类介绍(包括 ResponseEntity、 RestTemplate、WebUtils 等)

    此部分内容将包含 ResponseEntity. RestTemplate.WebUtils 等 1. ResponseEntity ① Sprring Mvc 中作为方法的返回值使用法 @Reque ...

  6. 如何理解opencv, python-opencv 和 libopencv?

    转:   OpenCV is a computer vision library written using highly optimized C/C++ code. It makes use of ...

  7. Servlet 上传下载文件

    上传文件 1)在表单中使用表单元素 <input type=“file” />,浏览器在解析表单时,会自动生成一个输入框和一个按钮 2)表单需要上传文件时,需指定表单 enctype 的值 ...

  8. phpstorm 断点调试 傻瓜教程

    前言: 简单介绍下为什么要用断点调试,很多人说我在代码调试的部位用var_dump 或者 exit 或者print_r来进行断点,但是当项目足够大的时候这样的做法就比较费时费力,因为你断点后需要删除原 ...

  9. Three.js学习笔记03--光

    1. 光源基类 在Threejs中,光源用Light表示,它是所有光源的基类.它的构造函数是: THREE.Light ( hex ) 它有一个参数hex,接受一个16进制的颜色值.例如要定义一种红色 ...

  10. 时时监听input内容的改变

    心得:我们都知道input有一个change事件,但是是在input元素失去焦点的时候发生,不能时时的监听input内容的改变. 刚开始的时候我是想用setInterval设置计时器的原理定时监听in ...