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入门篇(十一)之neutron服务(控制节点)的部署与测试

    1.Neutron的介绍 Neutron 为整个 OpenStack 环境提供网络支持,包括二层交换,三层路由,负载均衡,防火墙和 *** 等.Neutron 提供了一个灵活的框架,通过配置,无论是开 ...

  2. 阿里云服务器ECS上ubuntu安装nginx后默认站点页面打开错误,显示无法访问此网站

    问题:在新买的阿里云服务器ECS上安装nginx后打开默认页面失败,如下图所示. 系统环境:Ubuntu 16.04.4 LTS64版本. 步骤回顾: root用户下运行命令 apt-get inst ...

  3. SAO Utils – SAO风格启动菜单

    SAO Utils 是一款拥有 SAO(刀剑神域)外观风格的启动器,搭载各种各样强大的小工具. 随时随地.在屏幕任何地方 按住鼠标左键和右键并向下拖动 即可呼出应用启动菜单(触控设备直接支持双指下滑手 ...

  4. Intellij IDEA创建maven项目无java文件问题

    在idea开发工具中创建工程时,点击右键没有创建包.接口.java类的提示, 如图: 解决之前的项目目录为: 针对这种情况,对idea开发工具做以下设置. 选择File->Project Str ...

  5. 如何在window服务器上搭建一个能代替ftp的传输工具

    通常对于服务器上的文件管理和数据传输都是利用ftp来实现,但随着存储技术的发展,数据资产的存储规模和复杂程度不断提高,传统的ftp传输显得有笨重.今天给大家介绍一款能够取代ftp的在线文档管理软件—— ...

  6. 【LDAP安装】在已编译安装的PHP环境下安装LDAP模块

    在已编译安装的PHP环境下安装LDAP模块 (乐维温馨提示:其他模块也能以这个方式安装) 1.在PHP源码包内找到ldap模块文件 cd php-5.6.37 cd ext/ldap/ 2.phpiz ...

  7. openstack系列文章(四)

    学习 openstack 的系列文章 - Nova Nova 基本概念 Nova 架构 openstack Log Nova 组件介绍 Nova 操作介绍 1. Nova 基本概念 Nova 是 op ...

  8. python—多任务版udp聊天机器人

    将多任务(多线程)引入到udp聊天机器人,可以实现同时发送消息和接收消息 import socket import threading def udp_send(udp_socket,ip,port) ...

  9. windows docker 安装cloudera/quickstart

    最近需要写一个大数据的项目,但是公司没有测试环境,真是cao蛋,没办法,只能自己搭建一个测试环境,所以就在本地电脑装一个cloudera/quickstart,这个是一个单节点的大数据平台, 是clo ...

  10. 最新!2016中国城市GDP排名出炉

    2017年1月20日,国家统计局公布:2016年中国国内生产总值GDP达744127亿元,同比增长6.7%,城市GDP方面:截至1月20日,全国大部分城市的去年经济运行数据已经公布,根据信息汇总,20 ...