[Leetcode Week5]Word Ladder II
Word Ladder II 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/word-ladder-ii/description/
Description
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
- Return an empty list if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Solution
class Solution {
private:
map<string, int> isVisited;
map<string, vector<string>> preVertex;
public:
bool canTrans(string a, string b) {
int count = 0;
for (int i = 0; i < a.length(); i++)
if (a[i] != b[i]) {
if (count == 0)
count++;
else
return false;
}
return count == 1;
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
vector<vector<string>> resultLists;
vector<string> adjacentWordOfEnd;
if (wordList.size() == 0)
return resultLists;
bool endWordExist = false;
for (auto& w: wordList)
if (w == endWord) {
endWordExist = true;
break;
}
if (!endWordExist)
return resultLists;
isVisited[beginWord] = 0;
queue<string> vq;
vq.push(beginWord);
string qfront;
bool flag = false;
while (!vq.empty()) {
qfront = vq.front();
vq.pop();
if (qfront == endWord)
break;
if (canTrans(qfront, endWord)) {
adjacentWordOfEnd.push_back(qfront);
flag = true;
continue;
}
if (flag)
continue;
int curLevel = isVisited[qfront];
for (auto& w: wordList) {
if (canTrans(qfront, w)) {
if (isVisited.count(w) == 0) {
isVisited[w] = curLevel + 1;
vq.push(w);
preVertex[w].push_back(qfront);
} else if (isVisited[w] == 1 + curLevel) {
preVertex[w].push_back(qfront);
}
}
}
}
if (adjacentWordOfEnd.empty())
return resultLists;
queue< stack<string> > pathQueue;
for (auto& w: adjacentWordOfEnd) {
stack<string> path;
path.push(endWord);
path.push(w);
pathQueue.push(path);
}
while (!pathQueue.empty()) {
stack<string> curPath(pathQueue.front());
pathQueue.pop();
string curVertex = curPath.top();
if (curVertex == beginWord) {
insertPath(resultLists, curPath);
} else if (preVertex[curVertex].size() == 1 && preVertex[curVertex].back() == beginWord) {
curPath.push(beginWord);
insertPath(resultLists, curPath);
} else {
for (int i = 1; i < preVertex[curVertex].size(); i++) {
stack<string> newPath(curPath);
newPath.push(preVertex[curVertex][i]);
pathQueue.push(newPath);
}
curPath.push(preVertex[curVertex][0]);
pathQueue.push(curPath);
}
}
return resultLists;
}
void insertPath(vector<vector<string>>& resultLists, stack<string>& reversePath) {
vector<string> path;
while (!reversePath.empty()) {
path.push_back(reversePath.top());
reversePath.pop();
}
resultLists.push_back(path);
}
};
解题描述
这道题是在leetcode上AC的第一道hard的题,花了一天。一开始想到的还是BFS,在Word Ladder的基础上,多记录下完整的路径。但是实际并没有这么简单。这道题要多考虑相同长度的所有路径的情况。所以我起初想到的解决的办法就是通过记录BFS树中所求路径上每一个点的父节点,然后通过获取endWord的所有父节点来向上回溯直到达到beginWord。但是这里我想少了一点,就是其实路径中间的节点也可以和endWord一样拥有多个父节点。解决了这个问题之后,没有过的测例表明,对于endWord同层节点的排除还没有做。所以就另外加了一个flag来标记以排除与endWord同层的点,这才最终AC。
[Leetcode Week5]Word Ladder II的更多相关文章
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- Java for LeetCode 126 Word Ladder II 【HARD】
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- [LeetCode] 126. Word Ladder II 词语阶梯 II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...
- [Leetcode Week5]Word Ladder
Word Ladder题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder/description/ Description Give ...
- [LeetCode] 126. Word Ladder II 词语阶梯之二
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- [Leetcode][JAVA] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- [LeetCode#128]Word Ladder II
Problem: Given two words (start and end), and a dictionary, find all shortest transformation sequenc ...
- leetcode 126. Word Ladder II ----- java
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
随机推荐
- Jenkins - 持续集成部署
1. 安装svn:用于checkout源码 (1)yum 安装:yum -y install subversion (2)查看svn版本信息:svnserver --version 2. 安装jdk ...
- 第一篇 Postman的初级使用之设置环境快速切换生成环境与测试环境
POSTMAN是有谷歌的开源工具,在开发调试.测试执行过程中使用频率非常广泛,本文将记录一些postman在测试中常见的一些配置和使用方法 一.基本的页面区域 略,很简单,大家都会看,再有,学习下面的 ...
- final 内部类 static
[Java中为什么会有final变量]: final这个关键字的含义是“这是无法改变的”或者“终态的”: 那么为什么要阻止改变呢? java语言的发明者可能由于两个目的而阻止改变: 1).效率问题: ...
- 学习materialize
<div class="container"> <div class="row"> </div> <div cla ...
- JQuery JTable根据某行的某个值来设置行的背景颜色
目录 描述 处理方法 参考 描述 某个表的数据是用JQuery的JTable插件进行展示的.现在需求是:当表中的master字段为true时,就将对应的整行的背景颜色设置为浅蓝色. 处理方法 在fie ...
- WCF 透明代理
现在我们通过类似的原理创建一个用于模拟WCF服务端和客户端工作原理的模拟程序.[源代码从这里下载] 目录 一.基本的组件和执行流程 二.创建自定义HttpHandler实现对服务调用请求的处理 三.定 ...
- [LOJ#6437][BZOJ5373]「PKUSC2018」PKUSC
[LOJ#6437][BZOJ5373]「PKUSC2018」PKUSC 试题描述 九条可怜是一个爱玩游戏的女孩子. 最近她在玩一个无双割草类的游戏,平面上有 \(n\) 个敌人,每一个敌人的坐标为 ...
- hdu4035 Maze 【期望dp + 数学】
题目链接 BZOJ4035 题解 神题啊...orz 不过网上题解好难看,数学推导不写\(Latex\)怎么看..[Latex中毒晚期] 我们由题当然能很快写出\(dp\)方程 设\(f[i]\)表示 ...
- BZOJ2631 tree(伍一鸣) LCT 秘制标记
这个题一看就是裸地LCT嘛,但是我wa了好几遍,这秘制标记...... 注意事项:I.*对+有贡献 II.先下传*再下传+(因为我们已经维护了+,不能再让*对+产生贡献)III.维护+用到size # ...
- 用JSR的@Inject代替@Autowired完成自动装配
从spring3.0开始spring支持JSR-330 的标准注解.主要是javax.inject这个包下的: 下面的例子用@Inject代替@Autowired.完成自动装配: MovieFinde ...