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. [Python]Python中的包(Package)

    参考官方文档中的Module和Glosssary中的描述.Module: https://docs.python.org/3/tutorial/modules.html#packagesGlossar ...

  2. centos 桥接配置 设置网络代理 lnmp搭建

    一.桥接配置 centos设置  编辑->虚拟网络编辑器->桥接模式->还原默认设置 虚拟机->设置->网络适配器->桥接 cd /etc/sysconfig/ne ...

  3. js函数柯里化,实现bind

    1.柯里化: 把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术. 举个栗子: 一个计算两数之和的函数,需要传递两个参数,柯里化 ...

  4. 用java从0生成一个简单的excel

    用java从0生成一个简单的excel 目标 用代码实现对一个excel的基础操作,包括创建,插入文字,(好像就这些了),生成的excel可以用wps打开,如果直接用c++的文件流会生成假的xls表格 ...

  5. 2.SSM整合_多表_一对一或多对一的增删改查

    一对一和多对一配置一样,这里就放到一起. 1.配置文件跟上一章一样,这里就不多写了,主要是Mapper映射文件 多 接口 public interface NewsMapper { public vo ...

  6. cf 744D

    一开始没看懂题解,想了好久(一整天)才想明白是枚举弦上点二分半径check角度,看了下clj的代码发现思路都一样就开始写了. 借鉴了一下clj的代码. 调了一个多小时. 几个注意点:看到好多 rand ...

  7. Springboot搭建SSM+JSP的web项目

    Springboot搭建SSM+JSP的web项目 一:创建项目结构: 项目结构分为三个部分: 1 后端项目开发文件: 包: Util         工具包 Mapper      db层 Serv ...

  8. python从入门到实践-10章文件和异常(括号问题)

    #!/user/bin/env python# -*- coding:utf-8 -*- # 1.从文件中读取数据with open('pi_digits.txt') as file_object: ...

  9. 通用类 对象和XML互转

    public class XMLHealper { /// <summary> /// 将自定义对象序列化为XML字符串 /// </summary> /// <para ...

  10. FFmpeg开发实战(四):FFmpeg 抽取音视频的音频数据

    如何使用FFmpeg抽取音视频的音频数据,代码如下: void adts_header(char *szAdtsHeader, int dataLen); // 使用FFmpeg从视频中抽取音频 vo ...