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. SSH方式登录github出现Permission denied (publickey)

    今天在公司上传了代码,回到家pull,结果竟然出现了“Permission denied (publickey)“这种东西.第一反应是key不对,可是上次明明用key登录过,不可能不对啊,难道是文件被 ...

  2. iOS面试知识点

    1 iOS基础 1.1 父类实现深拷贝时,子类如何实现深度拷贝.父类没有实现深拷贝时,子类如何实现深度拷贝. 深拷贝同浅拷贝的区别:浅拷贝是指针拷贝,对一个对象进行浅拷贝,相当于对指向对象的指针进行复 ...

  3. Android——SQLite实现面向对象CRUD

    android中SQLite的使用,事实上倒也不难.可是与JDBC操作数据库相比,这个还是有点不顺手,并且我好久没写底层的封装了,使用SSM框架这些都不须要考虑......好了,废话不多说.以下直接建 ...

  4. 一些基础的.net用法

    一.using 用法 using 别名设置 using 别名 = System.web 当两个不同的namespace里有同名的class时.可以用 using aclass = namespace1 ...

  5. 部分GDAL工具功能简介

    主要转自http://blog.csdn.net/liminlu0314?viewmode=contents 部分GDAL工具功能简介 gdalinfo.exe 显示GDAL支持的各种栅格文件的信息. ...

  6. Javascript的性能瓶颈

    Javascript是单线程的,它的性能瓶颈在于频繁的DOM操作, 因为每次操作都会使浏览器重新绘制一次. 其实纯JS的执行的速度是很快的,可以把元素都攒到一块,一次性放到页面中. 或者,定义一个延时 ...

  7. javascript运动功能-分享到

    <script> //窗体载入,为div控件绑定事件 window.onload = function () { var div1 = document.getElementById('d ...

  8. [Python][MachineLeaning]Python Scikit-learn学习笔记1-Datasets&Estimators

    Scikit-learn官网:http://scikit-learn.org/stable/index.html Datasets 标准的数据集格式为一组多维特征向量组成的集合.数据集的标准形状(sh ...

  9. XML 解析中,如何排除控制字符

    XML 解析中,如何排除控制字符 今天在解析一个中文的 XML时,始终报错 PCDATA invalid Char value 21 in Entity ,查询了一下这个 21 的ascii 值,发现 ...

  10. pom.xml配置

    1:头部引用 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3 ...