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 ...
随机推荐
- 数据预处理之数据规约(Data Reduction)
数据归约策略 数据仓库中往往具有海量的数据,在其上进行数据分析与挖掘需要很长的时间 数据归约 用于从源数据中得到数据集的归约表示,它小的很多,但可以产生相同的(几乎相同的)效果 数据归约策略 维归约 ...
- 02Qt信号与槽(1)
信号与槽 1.概述 信号和槽机制是 Qt 的核心机制,信号和槽是一种高级接口,应用于对象之间的通信,它是 Qt 的核心特性,也是 Qt 区别于其他工具包的重要地方.信号和槽是 Qt 自行定义的一种 ...
- destoon后台权限-不给客户创始人权限并屏蔽部分功能
1.根目录下后台入口文件admin.php $_founder = $CFG['founderid'] == $_userid ? $_userid : 0; // $CFG['founderid ...
- nginx静态资源web服务
静态资源:非服务器动态运行生成的文件 浏览器端渲染:html ,css,js 图片:jpeg,gif,png 视频:flv ,mpeg 文件:txt,等任意下载文件 静态资源服务场景:CDN 文件读取 ...
- 使用nohup+& 踩到的坑
首先分清楚nohup与&: &是指在后台运行一般在执行命令后,都会显式的在前台执行,当Ctrl+C后进程回宕掉,但是 在命令后加&,即使Ctrl+C,程序还在进行,但是,当关闭 ...
- AJAX小练习
/index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pa ...
- stm32L0工程建立(HAL+IAR,无cubemx)
https://files.cnblogs.com/files/CodeWorkerLiMing/STM32HAL%E5%BA%93%E5%AD%A6%E4%B9%A0%E2%80%94%E5%B7% ...
- ACM-ICPC 2015 Shenyang Preliminary Contest B. Best Solver
The so-called best problem solver can easily solve this problem, with his/her childhood sweetheart. ...
- Python之code对象与pyc文件(二)
上一节:Python之code对象与pyc文件(一) 创建pyc文件的具体过程 前面我们提到,Python在通过import或from xxx import xxx时会对module进行动态加载,如果 ...
- day03 set集合,文件操作,字符编码以及函数式编程
嗯哼,第三天了 我们来get 下新技能,集合,个人认为集合就是用来list 比较的,就是把list 转换为set 然后做一些列表的比较啊求差值啊什么的. 先看怎么生成集合: list_s = [1,3 ...