Word Ladder II Graph
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.
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的更多相关文章
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- 18. Word Ladder && Word Ladder II
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
- 126. Word Ladder II(hard)
126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
- 126. Word Ladder II
题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...
随机推荐
- RabbitMQ 安装 rabbitmq_delayed_message_exchange插件
rabbitmq_delayed_message_exchange插件主要是实现延迟队列 一.下载插件 下载地址:http://www.rabbitmq.com/community-plugins.h ...
- 微信小程序:实现日历功能
一.功能描述 实现日历功能 二. 代码实现 1. index.wxml <view class='wrap'> <view> <view class='date-show ...
- Quartz.net 定时任务在IIS中没有定时执行
问题:Quartz.net 定时任务在项目部署到IIS中发现没有定时执行 解决方案: 1.在服务器上装一个360(自带自动刷新功能),在工具——>自动刷新——>自动刷新勾上 然后再设置一下 ...
- docker run 和docker start的区别
docker run 只在第一次运行时使用,将镜像放到容器中,以后再次启动这个容器时,只需要使用命令docker start 即可. docker run相当于执行了两步操作:将镜像放入容器中(doc ...
- 文本编辑器 vi/vim 的使用
文本编辑器 vi/vim 一.启动与退出 1. vim 2. vim 文件名(可以是存在的文件,也可以是不在的文件) 3.退出 :q 或者:x 在非“插入”模式二.vi/vim的工作模式 1.正常 ...
- Netty源码分析第5章(ByteBuf)---->第8节: subPage级别的内存分配
Netty源码分析第五章: ByteBuf 第八节: subPage级别的内存分配 上一小节我们剖析了page级别的内存分配逻辑, 这一小节带大家剖析有关subPage级别的内存分配 通过之前的学习我 ...
- partprobe命令详解
基础命令学习目录首页 原文链接:https://www.jb51.net/LINUXjishu/389836.html linux上,在安装系统之后,可否创建分区并且在不重新启动机器的情况下系统能够识 ...
- linux获得命令使用帮助
1. 内部命令: help CMD 2. 外部命令: CMD --help 3. 命令手册: manual(所有命令) man CMD 分章节: 1: 用户命令(User Commands - /bi ...
- 使用sql查询mysql/oracle/sql server/gp数据库中指定表的字段信息(字段名/字段类型/字段长度/是否是主键/是否为空)
1,根据数据库类型拼接不同URL /** * 根据类型不同拼接连接的URL * @param dbType 1:mysql.2:oracle.3:sql server.4:gp * @param ip ...
- Daily Scrum (2015/10/25)
今天终于到了周末的尾声,我们的组员也应该正常得投入到工作中了.这天晚上我(符美潇)和PM(潘礼鹏)和两个DEV开了一个小会,讨论一下我们本周的代码编写工作.我们了解到大家的代码阅读工作和相关知识的学习 ...