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 ...
随机推荐
- linux 安全狗安装问题
先下载安装包wget http://download.safedog.cn/safedog_linux64.tar.gz ls tar xzvf safedog_linux64.tar.gz ls c ...
- spring在service层获取session和request
首先要在web.xml增加如下代码: <listener> <listener-class>org.springframework.web.context.request.Re ...
- SQL Server 的通用分页显示存储过程(转载)
http://database.51cto.com/art/200512/12923.htm 建立一个 Web 应用,分页浏览功能必不可少.这个问题是数据库处理中十分常见的问题.经典的数据分页方法是: ...
- MVC Redirect 页面跳转不了
1:如果是AJAX调取后台控制器的方法,那么最后跳转的步骤应该在AJAX的success方法里面执行跳转 若果要在控制器跳转那么 应该是前端页面 进行表单提交 在控制器直接用 redire等跳转方法
- git 自己易忘的命令
1. git 更新远程分支列表 git remote update origin --prune git remote update origin -p 2. 查看远程分支: git branch - ...
- OpenGL(1)-环境搭建
写在前面 工作几年,开始沉心做技术,对自己的知识进行梳理. OpenGL是由khronos组织制定并维护的规范,并不是API. OpenGL在3.2之前采用的是立即渲染模式(固定渲染管线),3.2之后 ...
- Linux命令的那些事(二)
回顾Linux(一) 学习了以下命令: mkdir/rmdir/ls/rm/pwd/cd/touch/tree/man/--help 想具体了解请看上一篇文章跳转 在Linux中推荐大家使用subli ...
- Ubuntu下配置Anaconda
转自:https://blog.csdn.net/Horcham/article/details/57075388 安装Anaconda Ubuntu下似乎库中不自带Anaconda,是自带纯净的py ...
- mysql以zip安装,解决the service already exists(转载)
喵喵亲测可用: 转自:https://www.cnblogs.com/dichters/p/5929209.html mysql以zip安装, mysqld -install 报错:The serv ...
- CocoStuff—基于Deeplab训练数据的标定工具【五、训练成果分析】
一.说明 本文为系列博客第五篇,主要展示训练的结果,以及对训练进行分析. *注:暂未进行大量的数据训练以及IoU测算,目前只做到使用Matlab将训练结果的mat文件可视化. 二. *占坑