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. Python网络编程(基础总结、 入门经典)

    Linux下文件类型:     bcd -lsp          b(块.设备文件)          c(字符设备文件)          d(目录)          -(普通文件)       ...

  2. Leetcode 3. Longest Substring Without Repeating Characters (Medium)

    Description Given a string, find the length of the longest substring without repeating characters. E ...

  3. el-checkbox根据是否被选中执行不同的操作

    直接给el-checkbox绑定点击事件是没有效果的,因为它会被解析成其他形式的html,el-checkbox只是一个类名,因此,使用ts和jquery动态绑定事件: mounted() { $(& ...

  4. ai学习记录

    界面:多个预编辑区:制作图形,使用的图形放到工作区内,不使用在预编区.没有Ctrl/Alt+delete的概念,没有前后景颜色.新建:分辨率:矢量软件和分辨率无关: 新建时候不要勾选对齐到像素网格 存 ...

  5. Spring 集成Quartz

    在使用jdk的timer时发现无法在指定的日期进行执行任务.这便引入一个优秀的开源任务调度框架“quartz”.这里使用的是quartz-1.8.6版本.Quart的官网:http://www.qua ...

  6. 【bzoj3653】谈笑风生 DFS序+树状数组

    题目描述 给出一棵以1为根的有根树,q次询问,每次询问给出a和k,求点对 (b,c) 的数目,满足:a.b.c互不相同,b与a距离不超过k,且a和b都是c的祖先. 输入 输入文件的第一行含有两个正整数 ...

  7. P3032 [USACO11NOV]二进制数独Binary Sudoku

    题目描述 Farmer John's cows like to play an interesting variant of the popular game of "Sudoku" ...

  8. [洛谷P2763]试题库问题

    题目大意:有 $k$ 种类型和 $n$ 个题目,每个题目会适应部分类型,第$i$个类型需要$s_i$的题,一道题只能满足一种类型,现要求出满足所有类型的题目的方案 题解:看到匹配,想到网络流,源点向试 ...

  9. 【Linux】线程池

    首先,线程池是什么?顾名思义,就是把一堆开辟好的线程放在一个池子里统一管理,就是一个线程池. 其次,为什么要用线程池,难道来一个请求给它申请一个线程,请求处理完了释放线程不行么?也行,但是如果创建线程 ...

  10. 【BZOJ 2756】[SCOI2012]奇怪的游戏 二分+最大流

    这道题提醒我,要有将棋盘黑白染色的意识,尤其是看到相邻格子这样的条件的时候,然后就是要用到与其有关的性质与特点以体现其作用,这道题就是用到了黑格子与白格子之间的关系进行的,其出发点是每次一定会给一个黑 ...