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. Subsets II 解答

    Question Given a collection of integers that might contain duplicates, nums, return all possible sub ...

  2. 关于NetBeans IDE的配置优化

    首先,IDE的版本最好对应着JDK的版本. NetBeans优化的目的是提高NetBeans的启动速度和运行速度.下面介绍的NetBeans优化技巧是在版本6.0beta2上的优化.经过实验,大大提高 ...

  3. Atitit. 最佳实践 QA----减少cpu占有率--cpu占用太高怎么办

    Atitit. 最佳实践 QA----减少cpu占有率--cpu占用太高怎么办 跟个磁盘队列长度雅十,一到李80%走不行兰.... 1. 寻找线程too 多的.关闭... Taskman>> ...

  4. Hacker(十一)----黑客常用入侵方法

    Internet中,为了防止黑客入侵自己的电脑,就必须了解黑客入侵目标计算机的常用方法.黑客常用的入侵方法有数据驱动攻击.系统文件非法利用.伪造信息攻击.远端操纵等. 一.数据驱动攻击 数据驱动攻击是 ...

  5. 面试前的准备---C#知识点回顾----02

    经过昨天大量的简历投递,今天陆续收到面试邀约,明日准备大战一场,是死是活一试便知 1.数据库的范式 这算入门问题了吧,但凡是个数据库类的,都得问吧, 但我们在回答的时候开始背书啦 第一范式(1NF)无 ...

  6. 【css基础】文本对齐,水平对齐,垂直对齐

    先说水平对齐,那首先想到的就是text-align了,text-align:left,text-align:center,text- align:right,代表的就是左对齐,居中对齐和右对齐,需要注 ...

  7. HTML基础知识笔记(一)

    HTML定义 HTML指的是超文本标记语言 HTML不是编程语言,而是标记语言 标记语言是一套标记标签 HTML是用标记标签来描述网页   HTML标签1 <html></html& ...

  8. 前端--关于javascript基础

    首先javascript不是浏览器的附属品,只能说它大多数的运行环境是在浏览器中的,但又不仅仅局限于浏览器中.它是一门真正的程序设计语言,在这方面它和java.c.c++.c#是等同的,只不过它不直接 ...

  9. UIStepper UISlider UISwitch UITextField 基本控件

    1.UIStepper 步进控件 必掌握 1.重要属性: .value 初始值 .maximumValue 最大值 .minimumValue 最小值 .stepValue 间隔 2.常用事件: Va ...

  10. tableView特色用法

    // //  ViewController.m //  UITableView // //  Created by yhj on 15/12/15. //  Copyright © 2015年 QQ: ...