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. HDU 6191 2017ACM/ICPC广西邀请赛 J Query on A Tree 可持久化01字典树+dfs序

    题意 给一颗\(n\)个节点的带点权的树,以\(1\)为根节点,\(q\)次询问,每次询问给出2个数\(u\),\(x\),求\(u\)的子树中的点上的值与\(x\)异或的值最大为多少 分析 先dfs ...

  2. 并行Linq

    有时候我们对大批量数据进行处理,此时并行linq就起作用了. 并行查询 对于以下查询可以耗时会非常大,如下: ; var r = new Random(); , arraySize).Select(x ...

  3. Cocos2DX开发:记录遇到的一些问题和解决方法

    今天看了一下以前学习cocos2dx时记录的一些笔记,主要是在实际中遇到的一些问题,整理了一下,就成为了这篇文章,便于自己以后查找,也为一些新手提供点经验. 这篇文章会一直更新,将自己之后开发中遇到的 ...

  4. python的变量的命名规则以及定义

    1.变量,指计算机中存储数据的空间 2.变量的命名方式:变量名 = 值 3.变量的命名规定(标识符的命名规定): 只能由数字,字母,下划线组成(可以用中文但是不推荐) 不能以数字开头 不能与关键词重名 ...

  5. 【转载】钉钉开发c#帮助类 获取用户信息 DingHelper.cs

    using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using Sys ...

  6. 开始试用Dynamics 365

    1. 访问地址: https://trials.dynamics.com/Dynamics365/Signup/ ,默认选择第一个应用,也可以选择其他的,不影响,之后还可以添加更多的应用程序. 2. ...

  7. 论文阅读 | Formalizing Visualization Design Knowledge as Constraints: Actionable and Extensible Models in Draco

    1. Introduction 程序员编写的可视化图表与专家眼中的设计标准总存在差距.我们无法每次都向可视化专家咨询设计上的意见,所以我们需求将设计标准,研究成果应用于自动化设计工具的正式框架,这些工 ...

  8. mysql 数据库备份和恢复

    物理备份对比逻辑备份 物理备份是指直接复制包含数据的文件夹和文件.这种类型的备份适用于大数据量且非常重要,遇到问题需要快速回复的数据库. 逻辑备份保存能够代表数据库信息的逻辑结构(CREATE DAT ...

  9. Python中remove,pop,del的区别

    先上题:写出最终打印的结果 a = [1, 2, 3, 4] for x in a: a.remove(x) print(a) print("=" * 20) b = [1, 2, ...

  10. .NET处理Json的几种方式

    序列化里的xml,soap,binary在上一篇文章里面已经说过了,这篇主要说json. json是目前非常流行的一种序列化数据的方式,很多api都采用的是json,结构简洁,容易理解,适用性强,逐渐 ...