图-搜索-BFS-DFS-126. 单词接龙 II
2020-03-19 13:10:35
问题描述:
给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:
- 每次转换只能改变一个字母。
- 转换过程中的中间单词必须是字典中的单词。
说明:
- 如果不存在这样的转换序列,返回一个空列表。
- 所有单词具有相同的长度。
- 所有单词只由小写字母组成。
- 字典中不存在重复的单词。
- 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"] 输出:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"] 输出: [] 解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。
问题求解:
总体思路是先通过BFS搜索最小步数,并且记录BFS树,之后使用DFS得到路径。这里有个地方需要特别注意的是,在构建BFS树的时候,需要在某一层全部遍历结束后再把下一层的一起加入used中,否则会少掉一些上层到下层的边。
时间复杂度:O(n)
List<List<String>> res = new ArrayList<>();
Set<String> dict = new HashSet<>();
Map<String, Set<String>> graph = new HashMap<>();
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
for (String s : wordList) dict.add(s);
if (!dict.contains(endWord)) return res;
int step = bfs(beginWord, endWord);
if (step == -1) return res;
dfs(beginWord, endWord, new ArrayList<>(), step + 1);
return res;
}
private void dfs(String begin, String end, List<String> curr, int step) {
curr.add(begin);
if (curr.size() == step) {
if (curr.get(step - 1).equals(end)) res.add(new ArrayList<>(curr));
}
else {
for (String next : graph.get(begin)) {
dfs(next, end, curr, step);
}
}
curr.remove(curr.size() - 1);
}
private int bfs(String begin, String end) {
boolean flag = false;
Queue<String> q = new LinkedList<>();
Set<String> used = new HashSet<>();
q.add(begin);
used.add(begin);
int step = 0;
while (!q.isEmpty()) {
if (flag) return step;
int size = q.size();
Set<String> layer_used = new HashSet<>();
for (int k = 0; k < size; k++) {
String curr = q.poll();
if (!graph.containsKey(curr)) graph.put(curr, new HashSet<>());
char[] chs = curr.toCharArray();
for (int i = 0; i < chs.length; i++) {
char ch = chs[i];
for (char c = 'a'; c <= 'z'; c++) {
if (c == ch) continue;
chs[i] = c;
String next = new String(chs);
if (next.equals(end)) flag = true;
if (!dict.contains(next) || used.contains(next)) continue;
graph.get(curr).add(next);
q.add(next);
layer_used.add(next);
}
chs[i] = ch;
}
}
step += 1;
used.addAll(layer_used);
}
return -1;
}
图-搜索-BFS-DFS-126. 单词接龙 II的更多相关文章
- Java实现 LeetCode 126 单词接龙 II
126. 单词接龙 II 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列.转换需遵循如下规则: ...
- Leetcode 126.单词接龙II
单词接龙II 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列.转换需遵循如下规则: 每次转换只能 ...
- [LeetCode] 126. 单词接龙 II
题目链接 : https://leetcode-cn.com/problems/word-ladder-ii/ 题目描述: 给定两个单词(beginWord 和 endWord)和一个字典 wordL ...
- 126. 单词接龙 II
题目: 链接:https://leetcode-cn.com/problems/word-ladder-ii/ 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出 ...
- LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...
- PAT A1021 Deepest Root (25 分)——图的BFS,DFS
A graph which is connected and acyclic can be considered a tree. The hight of the tree depends on th ...
- 搜索入门_简单搜索bfs dfs大杂烩
dfs题大杂烩 棋盘问题 POJ - 1321 和经典的八皇后问题一样. 给你一个棋盘,只有#区域可以放棋子,同时同一行和同一列只能有一个棋子. 问你放k个棋子有多少种方案. 很明显,这是搜索题. ...
- hdu 4771 Stealing Harry Potter's Precious (2013亚洲区杭州现场赛)(搜索 bfs + dfs) 带权值的路径
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4771 题目意思:'@' 表示的是起点,'#' 表示的是障碍物不能通过,'.' 表示的是路能通过的: ...
- lintcode 单词接龙II
题意 给出两个单词(start和end)和一个字典,找出所有从start到end的最短转换序列 比如: 1.每次只能改变一个字母. 2.变换过程中的中间单词必须在字典中出现. 注意事项 所有单词具有相 ...
随机推荐
- 从iPhone X到三星S9,为何现在山寨还能如此肆无忌惮?
X到三星S9,为何现在山寨还能如此肆无忌惮?" title="从iPhone X到三星S9,为何现在山寨还能如此肆无忌惮?"> 曾几何时,以"土豪金&qu ...
- JavaScript 语言精粹笔记3
方法 毒瘤 糟粕 记录一下阅读蝴蝶书的笔记,本篇为书中最后一部分:方法.代码风格.优美的特性.毒瘤.糟粕等. 方法 这一章主要介绍了一些方法集.这里写几个我不太熟悉的方法和要点吧. array.joi ...
- rbenv、fish 與 VSCode 設置之路
在最新的 VSCode 1.3.1 版裡,Integrated Terminal 變得更加好用,但由於上游套件 xterm.js 的緣故,zsh 還是有無法捲動的問題.不過作為一個 Rails 開發者 ...
- python爬虫-纠正MD5错误认知
m = md5(".encode()) print(m.hexdigest()) # 25d55ad283aa400af464c76d713c07ad m = md5(".enco ...
- python爬虫-提取网页数据的三种武器
常用的提取网页数据的工具有三种xpath.css选择器.正则表达式 1.xpath 1.1在python中使用xpath必须要下载lxml模块: lxml官方文档 :https://lxml.de/i ...
- ORB-SLAM2 运行 —— ROS + Android 手机摄像头
转载请注明出处,谢谢 原创作者:Mingrui 原创链接:https://www.cnblogs.com/MingruiYu/p/12404730.html 本文要点: ROS 配置安装 解决 sud ...
- 字符串、bute[]数组和十六进制字符串的相互转换
1.字符串转换成十六进制字符串 public static String str2HexStr(String str) { if (EncodingUtil.isEmpty(str)) { retur ...
- RabbitMQ面试题集锦(精选)(另附思维导图)
1.使用RabbitMQ有什么好处? 1.解耦,系统A在代码中直接调用系统B和系统C的代码,如果将来D系统接入,系统A还需要修改代码,过于麻烦! 2.异步,将消息写入消息队列,非必要的业务逻辑以异步的 ...
- 获取View的快照
//获取快照 - (UIView*)customSnapshotInView:(UIView*)inview { UIView *snapshot = [inview snapshotViewAfte ...
- python 关于函数递归调用自己
爬取b站博人传 每页短评20个,页数超过1000页, 代码如下 import requests import json import csv def main(start_url): headers ...