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. Linux服务器挂死案例分析

    问题现象: 在linux服务器上运行一个指定的脚本时,就会出现无数个相同进程的,而且不停的产生,杀也杀不掉,最后系统就陷入死循环,无法登陆,只能人工去按机器的电源键才可以.这够崩溃的吧? 问题分析过程 ...

  2. Longest Common Prefix 解答

    Question Write a function to find the longest common prefix string amongst an array of strings. Solu ...

  3. WPF弹出对话确认框

    MessageBoxResult mr = CMessageBox.ShowQuestionMessage("点击“是”继续,点击“否”取消.", "确认删除?" ...

  4. Direct3D 顶点缓存

    今天我们来学习下Direct3D的顶点和顶点缓存,首先我们需要在场景中绘制一些物体,物体都是由多个三角形组成,每一个三角形由三个顶点组成,我们来看下面一个NPC的模型 左图:正常的模型         ...

  5. eclipse里添加类似myeclipse打开当前操作目录

    1.开打eclipse ide,依次run->external tools->external tools configuration 2.在Program下,new一个自己定义的prog ...

  6. 多线程程序 怎样查看每个线程的cpu占用

    可以用下面的命令将 cpu 占用率高的线程找出来: ps H -eo user,pid,ppid,tid,time,%cpu,cmd --sort=%cpu 这个命令首先指定参数'H',显示线程相关的 ...

  7. Android应用程序资源的编译和打包过程分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/8744683 我们知道,在一个APK文件中,除了 ...

  8. Hacker(13)----搜集目标计算机的重要信息

    扫描与嗅探攻防 黑客若要发起入侵攻击,他需要做好充分的准备的工作,首先通过嗅探和扫描等操作来搜索信息,从而确定目标计算机,以便准确发出攻击.嗅探和扫描操作可以利用专业的软件工具实现,如X-Scan.S ...

  9. css_day5

  10. a标签伪类的顺序

    在一次开发项目中,我用a链接来做效果,测试的时候发现,a:hover被点击后的效果就不再了!我百度才知道,原来在css写a链接也是有顺序之分的. 顺序应该是: a:link a标签还未被访问的状态: ...