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系列的更多相关文章

  1. [LeetCode] Word Ladder 词语阶梯

    Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...

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

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

  3. LeetCode:Word Ladder I II

    其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...

  4. 【leetcode】Word Ladder

    Word Ladder Total Accepted: 24823 Total Submissions: 135014My Submissions Given two words (start and ...

  5. 【leetcode】Word Ladder II

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

  6. 18. Word Ladder && Word Ladder II

    Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...

  7. [Leetcode][JAVA] Word Ladder II

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

  8. LeetCode127:Word Ladder II

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

  9. 【LeetCode OJ】Word Ladder II

    Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...

随机推荐

  1. 基于matlab的蓝色车牌定位与识别---识别

    接着昨天的工作,把最后一部分识别讲完. 关于字符识别这块,一种最省事的办法是匹配识别,将所得的字符和自己的标准字符库相减,计算所得结果,值最小的即为识别的结果.不过这种方法是在所得字符较为标准的情况, ...

  2. CF-1143D. The Beatles

    题意:有间隔为k的n个点在数轴上,下标为 \(1,k+1, 2*k+1,\cdots (n-1)*k+1\) 首尾相接.设起点为s,步长为L,而现在只知道s距离最近的点的距离为a,和(s+L)距离最近 ...

  3. Centos7离线部署kubernetes 1.13集群记录

    一.说明 本篇主要参考kubernetes中文社区的一篇部署文章(CentOS 使用二进制部署 Kubernetes 1.13集群),并做了更详细的记录以备用. 二.部署环境 1.kubernetes ...

  4. Helm入门

    前言:Helm是GO语言编写的,是管理kubernetes集群中应用程序包的客户端工具.Helm是类似于centos上的yum工具或Ubuntu上的apt-get工具.对于应用发布者而言,可以通过He ...

  5. DELL PowerEdge R620安装Windows server(你想将windows安装在何处”找不到任何本地磁盘,“找不到驱动器”)已解决!

    你可能碰到过DELL服务器上安装Windows server系列系统时无法识别或找不到硬盘的问题,对于DELL PowerEdge11-14代机器的,大家可以采用DELL的Lifecycle cont ...

  6. c# 输出不同时间的格式

    C#时间/日期格式大全,C#时间/日期函数大全 有时候我们要对时间进行转换,达到不同的显示效果 默认格式为:2005-6-6 14:33:34 如果要换成成200506,06-2005,2005-6- ...

  7. poj-2533 longest ordered subsequence(动态规划)

    Time limit2000 ms Memory limit65536 kB A numeric sequence of ai is ordered if a1 < a2 < ... &l ...

  8. source insight

    关于source inlight的版本 http://www.camnpr.com/archives/559.html   最新版本 http://www.sourceinsight.com/upda ...

  9. Linux学习-系统基本设定

    网络设定 (手动设定与 DHCP 自动取得) 网络其实是又可爱又麻烦的玩意儿,如果你是网络管理员,那么你必须要了解局域网络内的 IP, gateway, netmask 等参数,如果还想要连上 Int ...

  10. 迷宫问题&MakeFile

    先看一个有意思的问题, 我们定义一个二维数组表示迷宫. 它表示一个迷宫, 其中的1表示墙壁,0表示可以走的路, 只能横着走或竖着走,不能斜着走, 我们要编程序找出从左上角到右下角的路线.其实这个问题可 ...