Question

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["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.

Solution

Two major diffrences compared with "Word Ladder"

1. We should record path, i.e previous nodes

2. Only when stepNums changes can we remove this node from wordDict

注意的点有三个:

1. Queue中的数据结构

2. 什么时候判断不再遍历这个点?

当这个点已经在之前的层中被遍历(即当前步数大于之前的步数)=>需要一个Map来记录最少的步数

3. 什么时候判断不再遍历最后值为end的点?=>设置一个变量,记录第一个遍历到end值的步数。之后再遍历到end值,步数要与其比较。

 class WordNode {
public String word;
public WordNode prev;
public int level;
public WordNode (String word, WordNode prev, int level) {
this.word = word;
this.prev = prev;
this.level = level;
}
} public class Solution {
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return a list of lists of string
*/
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
// write your code here
List<List<String>> result = new ArrayList<>();
if (dict == null) {
return result;
}
dict.add(start);
dict.add(end);
// get adjacent list
Map<String, Set<String>> adjacentList = getNeighbors(dict);
Map<String, Integer> visited = new HashMap<>();
int prevLevel = 0;
Queue<WordNode> queue = new ArrayDeque<>();
queue.offer(new WordNode(start, null, 1));
// bfs
while (!queue.isEmpty()) {
WordNode cur = queue.poll();
if (end.equals(cur.word)) {
if (prevLevel == 0 || cur.level == prevLevel) {
prevLevel = cur.level;
addRecordToResult(result, cur);
} else {
break;
}
} else {
Set<String> neighbors = adjacentList.get(cur.word);
if (neighbors == null || neighbors.size() == 0) {
continue;
}
Set<String> removeSet = new HashSet<>();
for (String str : neighbors) {
if (visited.containsKey(str)) {
int visitedLevel = visited.get(str);
if (cur.level + 1 > visitedLevel) {
removeSet.add(str);
continue;
}
}
visited.put(str, cur.level + 1);
queue.offer(new WordNode(str, cur, cur.level + 1));
}
neighbors.removeAll(removeSet);
}
}
return result;
} private Map<String, Set<String>> getNeighbors(Set<String> dict) {
Map<String, Set<String>> map = new HashMap<>();
for (String str : dict) {
map.put(str, new HashSet<String>());
char[] arr = str.toCharArray();
int len = arr.length;
for (int i = 0; i < len; i++) {
char prev = arr[i];
for (char j = 'a'; j <= 'z'; j++) {
if (prev == j) {
continue;
}
arr[i] = j;
String newStr = new String(arr);
if (dict.contains(newStr)) {
map.get(str).add(newStr);
}
}
arr[i] = prev;
}
}
return map;
} private void addRecordToResult(List<List<String>> result, WordNode end) {
List<String> record = new ArrayList<>();
while (end != null) {
record.add(end.word);
end = end.prev;
}
Collections.reverse(record);
result.add(record);
}
}

Word Ladder II 解答的更多相关文章

  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. [LeetCode] Word Ladder II 词语阶梯之二

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

随机推荐

  1. Google的Protocol Buffer格式分析

    [转]转自:序列化笔记之一:Google的Protocol Buffer格式分析 从公开介绍来看,ProtocolBuffer(PB)是google 的一种数据交换的格式,它独立于语言,独立于平台.作 ...

  2. 高精度快速幂(Java版)

    import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class Main { pu ...

  3. Java中ThreadLocal无锁化线程封闭实现原理

    虽然现在可以说很多程序员会用ThreadLocal,但是我相信大多数程序员还不知道ThreadLocal,而使用ThreadLocal的程序员大多只是知道其然而不知其所以然,因此,使用ThreadLo ...

  4. 禁用UITableViewCell 重用机制

    有时候不想让Cell重用,怎么办勒.接下来介绍两种方法 方法一 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAt ...

  5. XCode Could not launch &quot;&quot; failed to get the task for process

    在Xcode下编译project正常,在模拟器下执行正常,最后在真机上执行的时候出现了例如以下错误: Could not launch "FeedMeWorms" failed t ...

  6. 【Struts2】新建一个Struts2工程,初步体验MVC

    实现目标 地址栏输入http://localhost:88/Struts2HelloWorld/helloworld.jsp 输入用户名,交由http://localhost:88/Struts2He ...

  7. Android学习笔记—Windows下NDK开发简单示例

    该示例假设Android开发环境已经搭建完成,NDK也配置成功: 1.在Eclipse上新建Android工程,名称为ndkdemo.修改res\layout\activity_main.xml &l ...

  8. Chrome 开发者工具详解(2):Network 面板

    面板上包含了Elements面板.Console面板.Sources面板.Network面板. Timeline面板.Profiles面板.Application面板.Security面板.Audit ...

  9. MVC自我学起之MVCMusic开发中遇到问题:musicstore edit方法出错的原因和解决方法

    错误提示: 存储区更新.插入或删除语句影响到了意外的行数(0).实体在加载后可能被修改或删除.刷新 ObjectStateManager 项. 解决案: 1.在view中或model中增加隐藏id 1 ...

  10. mssql 判断sql语句的执行效率语句

    SET STATISTICS io ONSET STATISTICS time ONgo--========此处为sql代码段=============== select zxbh from t_yr ...