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:

  1. Only one letter can be changed at a time.
  2. 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的更多相关文章

  1. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

  2. Java for LeetCode 126 Word Ladder II 【HARD】

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  3. [LeetCode] 126. Word Ladder II 词语阶梯 II

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  4. LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...

  5. [Leetcode Week5]Word Ladder

    Word Ladder题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder/description/ Description Give ...

  6. [LeetCode] 126. Word Ladder II 词语阶梯之二

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  7. [Leetcode][JAVA] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  8. [LeetCode#128]Word Ladder II

    Problem: Given two words (start and end), and a dictionary, find all shortest transformation sequenc ...

  9. leetcode 126. Word Ladder II ----- java

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

随机推荐

  1. jmeter无法启动的解决办法

    jmeter下载地址: 链接: https://pan.baidu.com/s/15YhiPH-kNVxISEZ4Mxf_WA     提取码: 25sv jdk 8.0 下载地址: 链接: http ...

  2. 接口自动化测试框架Karate入门

    介绍 在这篇文章中,我们将介绍一下开源的Web-API自动化测试框架--Karate Karate是基于另一个BDD测试框架Cucumber来建立的,并且共用了一些相同的思想.其中之一就是使用Gher ...

  3. cocos2d-x 精灵

    Sprite有两个父类:BatchableNode批量创建精灵(大量重复的比如子弹)和pyglet.sprite.Sprite. 精灵的创建

  4. django2.0 以上版本安装 xadmin

    1.xadmin的下载 源码包下载地址: https://github.com/sshwsfc/xadmin/tree/django2 2.使用命令安装xadmin pip install 你下载的压 ...

  5. Java实现网页截屏功能(基于phantomJs)

    公司最近有个需求:把用户第一次的测量身体信息和最近一次测量信息进行对比,并且需要把对比的数据截成图片可以发给用户(需要在不打开网页的情况下实时对网页进行截图然后保存到服务器上,返回图片地址),通过网上 ...

  6. 学习bash——数据流重定向

    一.概述 1. 数据流 定义:以规定顺序被读取一次的数据序列. 分类:标准输入(stdin).标准输出(stdout)和标准错误输出(stderr). 标准输出:指的是命令执行所回传的正确信息. 标准 ...

  7. 详细讲解Java中方法的重载和重写

    首先讲讲方法的重载: Java的重载就是在类中可以创建多个方法,它们具有相同的名字,但是却有不同的参数. 判断是否重载只有两个条件: 1)相同的方法名 2)不同的参数 具体为: A.方法参数类型不同 ...

  8. lintcode-74-第一个错误的代码版本

    74-第一个错误的代码版本 代码库的版本号是从 1 到 n 的整数.某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错.请找出第一个错误的版本号. 你可以通过 isBad ...

  9. SQL select 和SQL where语句

    一.SQL SELECT语句 用于从表中选取数据,结果被存储在一共结果表中(称为结果集) 1.语法: SELECT 列名称   FROM  表名称 以及: SELECT * FROM 表名称 注:SQ ...

  10. Windows 64下elasticsearch-1.7.1集群 安装、启动、停止

    elasticsearch-1.7.1 (es Windows 64) 安装.启动.停止的详细记录 https://blog.csdn.net/qq_27093465/article/details/ ...