Word Ladder系列
1.Word Ladder
问题描述:
给两个word(beginWord和endWord)和一个字典word list,找出从beginWord到endWord之间的长度最长的一个序列,条件:
1.字典中的每个单词只能使用一次;
2.序列中的每个单词都必须是字典中的单词;
例如:
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
注意:
如果找不到合适的序列,返回0;
所有的单词长度都是一样的;
所有的单词都只由小写字母组成。
思路:
采用DFS依次遍历
代码如下:
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
unordered_set<string> s1 = {beginWord}; // Front end
unordered_set<string> s2 = {endWord}; // Back end
wordDict.erase(beginWord);
wordDict.erase(endWord);
return ladderLength(s1, s2, wordDict, );
}
private:
int ladderLength(unordered_set<string>& s1, unordered_set<string>& s2, unordered_set<string>& wordDict, int level) {
if (s1.empty()) // We can't find one.
return ;
unordered_set<string> s3; // s3 stores all words 1 step from s1.
for (auto word : s1) {
for (auto& ch : word) {
auto originalCh = ch;
for (ch = 'a'; ch <= 'z'; ++ ch) {
if (ch != originalCh) {
if (s2.count(word)) // We found one.
return level + ;
if (wordDict.count(word)) {
wordDict.erase(word); // Avoid duplicates.
s3.insert(word);
}
}
}
ch = originalCh;
}
}
// Continue with the one with smaller size.
return (s2.size() <= s3.size()) ? ladderLength(s2, s3, wordDict, level + ) : ladderLength(s3, s2, wordDict, level + );
}
};
1.Word Ladder II
问题描述:给两个word(beginWord和endWord)和一个字典word list,找出从beginWord到endWord之间所有长度最短的序列,条件:
1.一次只能改变一个字符
2.每个中间的单词必须在字典中
思路:
Treat each word as a node of a tree. There are two trees. One tree's root node is "beginWord", and the other tree's root node is "endWord".
The root node can yield all his children node, and they are the second layer of the tree. The second layer can yield all their children, then we get the third layer of the tree, ... , and so on.
When one tree yield a new child, we search it in the last layer of the other tree. If we find an identical node in that tree, then we get some ladders connect two roots("beginWord" -> ... -> "endWord").
Another thing should be considered is: two(or more) different nodes may yield an identical child. That means the child may have two(or more) parents. For example, "hit" and "hot" can both yield "hat", means "hat" has two parents.
So, the data struct of tree-node is:
class Node {
public:
string word;
vectror<Node*> parents;
Node(string w) : word(w) {}
}
Note: we don't need a children field for Node class, because we won't use it.
Two nodes are considered equal when their word field are equal. So we introduce an compare function:
bool nodecmp(Node* pa, Node* pb)
{
return pa->word < pb->word;
}
Then we use nodecmp as the compare function to build a node set.
typedef bool (*NodeCmper) (Node*, Node*);
typedef set<Node*, NodeCmper> NodeSet;
NodeSet layer(nodecmp);
Then we can store/search pointers of nodes in node set layer. For example:
Node node1("hit"), node2("hot"), node3("hat");
layer.insert(&node1);
layer.insert(&node2);
layer.insert(&node3);
auto itr = layer.find(new Node("hot"));
cout << (*itr)->word; // output: hot
Using these data structures, we can solve this problem with bi-direction BFS algorithm. Below is the AC code, and it is very very fast.
class Node; typedef vector<string> Ladder;
typedef unordered_set<string> StringSet;
typedef bool (*NodeCmper) (Node*, Node*);
typedef set<Node*, NodeCmper> NodeSet; class Node
{
public:
string word;
vector<Node*> parents; Node(string w) : word(w) {}
void addparent(Node* parent) { parents.push_back(parent); } // Yield all children of this node, and:
// 1) If the child is found in $targetlayer, which means we found ladders that
// connect BEGIN-WORD and END-WORD, then we get all paths through this node
// to its ROOT node, and all paths through the target child node to its ROOT
// node, and combine the two group of paths to a group of ladders, and append
// these ladders to $ladders.
// 2) Elif the $ladders is empty:
// 2.1) If the child is found in $nextlayer, then get that child, and add
// this node to its parents.
// 2.2) Else, add the child to nextlayer, and add this node to its parents.
// 3) Else, do nothing.
void yieldchildren(NodeSet& nextlayer, StringSet& wordlist, NodeSet& targetlayer,
vector<Ladder>& ladders, bool forward)
{
string nextword = word;
for (int i = , n = nextword.length(); i < n; i++) {
char oldchar = nextword[i];
for (nextword[i] = 'a'; nextword[i] <= 'z'; nextword[i]++) {
if (wordlist.count(nextword)) {
// now we found a valid child-word, let's yield a child.
Node* child = new Node(nextword);
yield1(child, nextlayer, targetlayer, ladders, forward);
}
}
nextword[i] = oldchar;
}
} // yield one child, see comment of function `yieldchildren`
void yield1(Node* child, NodeSet& nextlayer, NodeSet& targetlayer,
vector<Ladder>& ladders, bool forward) {
auto itr = targetlayer.find(child);
if (itr != targetlayer.end()) {
for (Ladder path1 : this->getpaths()) {
for (Ladder path2 : (*itr)->getpaths()) {
if (forward) {
ladders.push_back(path1);
ladders.back().insert(ladders.back().end(), path2.rbegin(), path2.rend());
} else {
ladders.push_back(path2);
ladders.back().insert(ladders.back().end(), path1.rbegin(), path1.rend());
}
}
}
} else if (ladders.empty()) {
auto itr = nextlayer.find(child);
if (itr != nextlayer.end()) {
(*itr)->addparent(this);
} else {
child->addparent(this);
nextlayer.insert(child);
}
}
} vector<Ladder> getpaths()
{
vector<Ladder> ladders;
if (parents.empty()) {
ladders.push_back(Ladder(, word));
} else {
for (Node* parent : parents) {
for (Ladder ladder : parent->getpaths()) {
ladders.push_back(ladder);
ladders.back().push_back(word);
}
}
}
return ladders;
}
}; bool nodecmp(Node* pa, Node* pb)
{
return pa->word < pb->word;
} class Solution {
public:
vector<Ladder> findLadders(string begin, string end, StringSet& wordlist) {
vector<Ladder> ladders;
Node headroot(begin), tailroot(end);
NodeSet frontlayer(nodecmp), backlayer(nodecmp);
NodeSet *ptr_layerA = &frontlayer, *ptr_layerB = &backlayer;
bool forward = true; if (begin == end) {
ladders.push_back(Ladder(, begin));
return ladders;
} frontlayer.insert(&headroot);
backlayer.insert(&tailroot);
wordlist.insert(end);
while (!ptr_layerA->empty() && !ptr_layerB->empty() && ladders.empty()) {
NodeSet nextlayer(nodecmp);
if (ptr_layerA->size() > ptr_layerB->size()) {
swap(ptr_layerA, ptr_layerB);
forward = ! forward;
}
for (Node* node : *ptr_layerA) {
wordlist.erase(node->word);
}
for (Node* node : *ptr_layerA) {
node->yieldchildren(nextlayer, wordlist, *ptr_layerB, ladders, forward);
}
swap(*ptr_layerA, nextlayer);
} return ladders;
}
};
Word Ladder系列的更多相关文章
- [LeetCode] Word Ladder 词语阶梯
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- 【leetcode】Word Ladder
Word Ladder Total Accepted: 24823 Total Submissions: 135014My Submissions Given two words (start and ...
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- 18. Word Ladder && Word Ladder II
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- [Leetcode][JAVA] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode127:Word Ladder II
题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- 【LeetCode OJ】Word Ladder II
Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...
随机推荐
- STL之stack操作
c++ stl栈stack介绍 C++ Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,——也就是说实现了一个先进后出(FILO)的数据结构. c++ stl栈stack的头文件 ...
- $GLOBALS['HTTP_RAW_POST_DATA']与$_POST的区别
$HTTP_RAW_POST_DATA The RAW / uninterpreted HTTP POst information can be accessed with: $GLOBALS ...
- Voyager的数据库操作与Bread Builder,解决国内打开网速超级慢的问题
Products表的创建: Bread Builder 伟大的XX封了谷哥,所以有关网站实在是打不开,正准备放弃的时候,突然发现问题了,对就是这个网站ajax.googleapis.com,由于调用的 ...
- 12.Yii2.0框架视图模版继承与模版相互调用
目录 模板渲染的两种方式 加载视图 index.php 和 about.php 页面 建立控制器HomeController php 新建模板 home\index.php 新建模板home\abou ...
- matplotlib学习记录 二
# 绘制10点到12点的每一分钟气温变化折线图 import random from matplotlib import pyplot as plt # 让matplotlib能够显示中文 plt.r ...
- LeetCode(162) Find Peak Element
题目 A peak element is an element that is greater than its neighbors. Given an input array where num[i ...
- 牛客网 Wannafly挑战赛21 灯塔
Z市是一座港口城市,来来往往的船只依靠灯塔指引方向.在海平面上,存在n个灯塔.每个灯塔可以照亮以它的中心点为中心的90°范围.特別地, 由于特殊限制,每个灯塔照亮范围的角的两条边必须要么与坐标轴平行要 ...
- cygwin的使用
参考资料: 对话 UNIX: 在 Windows 上使用 Cygwin Cygwin使用指南
- Java技术——Java泛型详解
.为什么需要泛型 转载请注明出处:http://blog.csdn.net/seu_calvin/article/details/52230032 泛型在Java中有很重要的地位,网上很多文章罗列各种 ...
- Jenkins自动化搭建测试环境(二)
Fork项目 找到项目 单击Fork 这时,会发送一个邮件到你的git邮箱中,点击链接即可完成fork 这样,这个工程就已经fork到自己的git上了 然后就可以下载这个工程到本机了 这里我们需要使用 ...