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. Binary Search Tree BST Template

    Use one queue + size variable public class Solution { public ArrayList<ArrayList<Integer>&g ...

  2. Largest Rectangle in Histogram 解答

    Question Given n non-negative integers representing the histogram's bar height where the width of ea ...

  3. 【转】linux文件系统之mount流程分析

    本质上,Ext3 mount的过程实际上是inode被替代的过程. 例如,/dev/sdb块设备被mount到/mnt/alan目录.命令:mount -t ext3 /dev/sdb /mnt/al ...

  4. Arithmetic Sequence(dp)

    Arithmetic Sequence Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 51  Solved: 19[Submit][Status][We ...

  5. C#操作IE

    操作IE主要使用两个Com Dll: 1.Microsoft Internet Controls 2.Microsoft HTML Object Library 使用Microsoft Interne ...

  6. VS2008 由于应用程序配置不正确,应用程序未能启动。重新安装应用程序可能会纠正这个问题。

    提示这个错误,自己的程序是在VS2008下编译的C/C++ win32程序,自己当时在win7上开发测试,都没有问题,正常使用,也在另一台xp系统上也试了,都没有问题.就发给客户了,没想到有些客户竟然 ...

  7. servlet基本概念

    一.servlet是一个供其它java程序调用的java类,比方tomcatserver,它不能独自执行,它的执行由servlet引擎来控制和调度. 二.servlet是单例,多线程 针对多个clie ...

  8. C++空类中的默认函数

    定义一个空的C++类,例如 class Empty { } 一个空的class在C++编译器处理过后就不再为空,编译器会自动地为我们声明一些member function,一般编译过去就相当于 cla ...

  9. html5lib-python doc

    http://html5lib.readthedocs.org/en/latest/ By default, the document will be an xml.etree element ins ...

  10. System.AccessViolationException: 尝试读取或写入受保护的内存 解决办法

    netsh winsock reset   --运行此命令解决 错误描述: 之前装的vs2010后 再又安装了vs2013 ,运行之前的vs2010项目 就出现以上错误 错误应用程序名称: w3wp. ...