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. 关于JQ中,新生成的节点on绑定事件失效的解决

    老旧的JQ库在做新生成DIV的click事件绑定,需要先绑定其现有的父元素,在追踪到需要事件绑定的子节点上 如以下这段代码$(".t_in").on("click&quo ...

  2. iptv

    # -*- coding: utf-8 -*- import datetime, time, json, re, os #from pwd import getpwnam #quality str_q ...

  3. linux的一些基础命令

    Linux是基于Unix的开源免费的操作系统,是部署服务器的很好选择. 系统:win10 工具:vm虚拟机+Xshell/CRT  虚拟机的系统为linux centos 7 首先看一下linux的基 ...

  4. 限制输入字数JS

    <tr> <th><b>说明内容:</b><span id="content">(500字以内)</span> ...

  5. [AtCoder3856]Ice Rink Game - 模拟

    Problem Statement An adult game master and N children are playing a game on an ice rink. The game co ...

  6. 文本在div中始终垂直居中

    如果是文本字数固定,在div中垂直居中,相信大家都会 这边分享个不固定文本在div中垂直居中的方法 html代码 <div class="box"> <div c ...

  7. App间相互跳转及图片分享

    A-app: Info--URL Types--URL Schemes:A-app(一个标识,允许别的app调用本App) info.plist 添加白名单: LSApplicationQueries ...

  8. 找一个数组的最大和的连续子数组(时间复杂度 O(n))

    设计思想 一开始的思想是求出全部的情况,再分别比较大小,这种方法适用于有限个数组,不适用于输入数组长度和内容的情况. 但也试着做了 int a[]= {-1,2,6,-10}; int size=4; ...

  9. linux操作命令之搜索命令

    1.文件搜索命令:locate 文件名 在后台数据库中按照文件名搜索,搜素速度更快 /var/lib/mlocate:#locate命令所搜索的后台数据库 updatedb:更新数据库 updated ...

  10. Java作业八(2017-10-30)

    public class TAutoPerson { public static void main(String args[]) { new Person(); new Person(); new ...