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.

The solution contains two steps 1 Use BFS to construct a graph. 2. Use DFS to construct the paths from end to start.Both solutions got AC within 1s.

The first step BFS is quite important. I summarized three tricks

1) Using a MAP to store the min ladder of each word, or use a SET to store the words visited in current ladder, when the current ladder was completed, delete the visited words from unvisited. That's why I have two similar solutions.

2) Use Character iteration to find all possible paths. Do not compare one word to all the other words and check if they only differ by one character.

3) One word is allowed to be inserted into the queue only ONCE. See my comments.

The idea is to use bfs build the graph level by level, use Map<String,Set> to store the parents of string, then use dfs to find the path.

 public class Solution {
List<List<String>> result;
HashMap<String, Set<String>> wordGraph;
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
result = new ArrayList<List<String>>();
if(dict == null || dict.size() == 0) return result;
wordGraph = new HashMap<String, Set<String>>();
wordGraph.put(start, new HashSet<String>());
LinkedList<String> queue = new LinkedList<String>();
HashSet<String> used = new HashSet<String>();
queue.add(start);
queue.add(null);
boolean flg = false;
while(queue.size() != 1){
String cur = queue.poll();
used.add(cur);
if(cur == null){
if(flg == true) break;
else queue.add(null);
}else{
char[] arr = cur.toCharArray();
for(int i = 0; i < cur.length(); i ++){
for(char j = 'a'; j <= 'z'; j ++){
if(arr[i] == j) continue;
char tmp = arr[i];
arr[i] = j;
String tmpString = String.valueOf(arr);
if(end.equals(tmpString)){
flg = true;
if(!wordGraph.containsKey(tmpString)){
Set<String> parents = new HashSet<String>();
parents.add(cur);
wordGraph.put(tmpString, parents);
}else{
wordGraph.get(tmpString).add(cur);
}
}else if(dict.contains(tmpString) && !used.contains(tmpString) && flg != true){
if(!wordGraph.containsKey(tmpString)){
Set<String> parents = new HashSet<String>();
parents.add(cur);
wordGraph.put(tmpString, parents);
}else{
wordGraph.get(tmpString).add(cur);
}
queue.add(tmpString); }
arr[i] = tmp;
}
}
}
}
if(wordGraph.containsKey(end))
findPath(end, start, new ArrayList<String>());
return result;
} private void findPath(String cur, String goal, ArrayList<String> row){
if(cur.equals(goal)){
row.add(0, cur);
result.add(row);
}else{
for(String pre : wordGraph.get(cur)){
row.add(0, cur);
findPath(pre, goal, new ArrayList<String>(row));
row.remove(0);
}
}
}
}

Word Ladder II Graph的更多相关文章

  1. 【leetcode】Word Ladder II

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

  2. 18. Word Ladder && Word Ladder II

    Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...

  3. LeetCode :Word Ladder II My Solution

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

  4. [leetcode]Word Ladder II @ Python

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

  5. LeetCode: Word Ladder II 解题报告

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

  6. [Leetcode Week5]Word Ladder II

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

  7. 126. Word Ladder II(hard)

    126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...

  8. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  9. 126. Word Ladder II

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...

随机推荐

  1. OpenStack入门篇(十九)之网络虚拟化基础

    1.Linux Bridge的基本概念 假设宿主机有 1 块与外网连接的物理网卡 eth0,上面跑了 1 个虚机 VM1,现在有个问题是: 如何让 VM1 能够访问外网?① 给 VM1 分配一个虚拟网 ...

  2. 很详细的SpringBoot整合UEditor教程

    很详细的SpringBoot整合UEditor教程 2017年04月10日 20:27:21 小宝2333 阅读数:21529    版权声明:本文为博主原创文章,未经博主允许不得转载. https: ...

  3. pycharm安装第三方库失败解决办法

    一.报错信息:[file][Default Settint]---Project Interpreter 点击 搜索suds安装模块报错 解决:依据上图提示找到C:\Program Files\Jet ...

  4. Tomcat 下载与安装

    下载地址:http://tomcat.apache.org 根据自己电脑的系统下载Core节点下不同的版本.   Tomcat文件目录结构 bin:存放启动与关闭Tomcat的脚本文件 conf:存放 ...

  5. 使用tensorflow进行mnist数字识别【模型训练+预测+模型保存+模型恢复】

      import sys,os sys.path.append(os.pardir) import numpy as np from tensorflow.examples.tutorials.mni ...

  6. SDN学习笔记

    SDN 什么是SDN SDN是一种框架和思想,核心诉求是通过软件控制网络,实现业务的自动化部署,为方便软件来控制网络,希望控制面和转发面是分离的. 例如,传统的交换机内部,由交换机负责具体的网络流量往 ...

  7. 进阶:2.GBDT算法梳理

    GBDT算法梳理 学习内容: 1.前向分布算法 2.负梯度拟合 3.损失函数 4.回归 5.二分类,多分类 6.正则化 7.优缺点 8.sklearn参数 9.应用场景 1.前向分布算法 在学习模型时 ...

  8. NO.8:自学python之路------并行socket网络编程

    摘要 一到放假就杂事很多,这次的作业比较复杂,做了一个周,进度又拖了.不过结果还不错. 正文 粘包 在上一节中,如果连续发送过多数据,就可能发生粘包.粘包就是两次发送的数据粘在一起被接收,损坏了数据的 ...

  9. 图解 Go 并发

    你很可能从某种途径听说过 Go 语言.它越来越受欢迎,并且有充分的理由可以证明. Go 快速.简单,有强大的社区支持.学习这门语言最令人兴奋的一点是它的并发模型. Go 的并发原语使创建多线程并发程序 ...

  10. hive创建临时函数

    add jar /home/hjl/sunwg/Lower.jar; create temporary function my_lower as ‘com.example.hive.udf.Lower ...