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. C# 神奇的Web services 请求超时问题 排查分析

    服务器上有两个接口,一个是Web Services(asmx文件)接口,一个是MVC API (普通的GET请求接口) 神奇的事情是这样的,只要我使用WebRequest请求两次,再使用Web Ser ...

  2. CentOS7x64 防火墙配置

    Firewall开启常见端口命令: firewall-cmd --zone=public --add-port=80/tcp --permanent firewall-cmd --zone=publi ...

  3. MT7688交叉编译环境配置

    在ubuntu下设置MT7688交叉编译环境,用于编译mt7688下使用的程序 1.首先在vmware下安装ubuntu64位,由于交叉编译工具需要64位系统,此次安装的是ubuntu14 2.在ub ...

  4. window下如何使用文本编辑器(如记事本)创建、编译和执行Java程序

    window下如何使用文本编辑器(如记事本)创建Java源代码文件,并编译执行 第一步:在一个英文目录下创建一个 .text 文件 第二步:编写代码 第三步:保存文件 方法一:选择 文件>另存为 ...

  5. ES8 async/await语法

    Async/await的主要益处是可以避免回调地狱(callback hell)问题 Chromium JavaScript引擎 从v5.5开始支持async/await功能,Chromium Jav ...

  6. javaweb聊天室源码免费

    效果:可擴展源碼,免費技術指導,電話13956301647 链接:https://pan.baidu.com/s/1FWV8DNWacGaEpAQEsWsNaw 提取码:b6gf

  7. Tensorboard可视化(关于TensorFlow不同版本引起的错误)

    # -*- coding: utf-8 -*-"""Created on Sun Nov 5 15:28:50 2017 @author: Administrator&q ...

  8. IIS集中化管理与编程REST API

    目录 一.       简介.... 1 二.       安装.... 1 三.       IIS Administration配置文件.... 2 四.       Web UI管理界面.... ...

  9. emWin洗衣机简易操作界面,含uCOS-III和FreeRTOS两个版本

    第3期:洗衣机简易操作界面 配套例子:V6-904_STemWin提高篇实验_洗衣机简易操作界面(uCOS-III)V6-905_STemWin提高篇实验_洗衣机简易操作界面(FreeRTOS) 例程 ...

  10. [Swift]LeetCode79. 单词搜索 | Word Search

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...