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 ...
随机推荐
- iOS中开源框架GPUImage的使用之生成libGPUImage.a文件和创建工程(一)
一.下载GPUImage (1)下载地址:https://github.com/BradLarson/GPUImage (2)下载后打开 GPUImage.xcodeproj 工程,选择真机运行该工 ...
- window下查杀占用端口的进程
一. 查找占用的端口进程号,比如8080 C:> netstat –ano|findstr 8080 C:\Users\chry>netstat -ano | findstr 8080 T ...
- JAVA 删除指定目录下指定文件类型的所有文件
public class DelFile { public static void main(String[] args) { File file = new File("C:\\DETEC ...
- 关于恶意说说自动在QQ空间转发的机制
有些很讨厌的带链接说说,只要你在手机打开它,就会自动转发,内容极其不雅 一怒之下我决定看个究竟首先,在此页开头有此关键语句: <iframe src="http://rtb.map.q ...
- js,jsp里将数据库Date类型获取出来后格式化显示于界面
js:new Date(rowdata.updateTime).format("yyyy-MM-dd hh:mm:ss") jsp: <fmt:formatDate valu ...
- SQL语句汇总(一)——数据库与表的操作以及创建约束
首先,非常感谢大家对上篇博文的支持,真是让本菜受宠若惊,同时对拖了这么久才出了此篇表示抱歉. 前言:此文旨在汇总从建立数据库到联接查询等绝大部分SQL语句.SQL语句虽不能说很多,但稍有时间不写就容易 ...
- Netty源码分析第1章(Netty启动流程)---->第1节: 服务端初始化
Netty源码分析第一章: Server启动流程 概述: 本章主要讲解server启动的关键步骤, 读者只需要了解server启动的大概逻辑, 知道关键的步骤在哪个类执行即可, 并不需要了解每一步的 ...
- Python函数式编程中map()、reduce()和filter()函数的用法
Python中map().reduce()和filter()三个函数均是应用于序列的内置函数,分别对序列进行遍历.递归计算以及过滤操作.这三个内置函数在实际使用过程中常常和“行内函数”lambda函数 ...
- [zabbix] zabbix从内部检测web页面
环境说明: 两台机器各运行一个tomcat实例,通过阿里云slb到后端,假设后端服务挂了一个,从外部访问整个服务还是可用的,所以需要从内部检测web页面. zabbix自带的web场景都是从外部检测w ...
- java第四次实验报告
课程:Java程序与设计 班级:1352 姓 名:池彬宁 小组成员: 20135212池彬宁 20135208贺邦 学号:20135212 成绩: 指导教师:娄嘉鹏 ...