Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

思想:宽度优先搜索(BFS)即可。(可从头往尾部搜,也可从尾往头部搜,)。

我的方案中,使用两个 hash_set 分别存储当前层和下一层结点,另一个 hash_set存储之前遍历过的结点。

class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
int ans = 0;
unordered_set<string> previousNodes;
vector<unordered_set<string> > node_levels(2);
int curLevel = 0; // which is index belong to vector node_levels.
node_levels[curLevel].insert(end);
ans++;
unordered_set<string>::iterator it;
while(!node_levels[curLevel].empty()) {
for(it = node_levels[curLevel].begin(); it != node_levels[curLevel].end(); ++it) {
for(size_t i = 0; i < it->size(); ++i) {
string node(*it);
for(node[i] = 'a'; node[i] <= 'z'; ++node[i]) {
if(node == start) return (ans+1); // output 1
if(previousNodes.count(node) || node_levels[curLevel].count(node) || node[i] == (*it)[i] || !dict.count(node))
continue;
node_levels[!curLevel].insert(node);
}
}
previousNodes.insert(*it);
}
node_levels[curLevel].clear();
curLevel = !curLevel;
ans++;
}
return 0; // output 2
}
};

Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"]

Return

  [
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]

Note:

  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

思想: 在 I 的基础之上, 加入 hash_map 记下每条边, 从 end 开始搜索,建立以 start 为源点,end 为汇点的图,然后从 start 开始深搜即可。

typedef pair<string, string> PAIR;
void getSolution(string &end, string& word, unordered_multimap<string, string> &map, vector<vector<string> > &vec, vector<string> &vec2) {
if(word == end) {
vec.push_back(vec2);
vec.back().push_back(word);
return;
}
pair<unordered_map<string, string>::iterator, unordered_map<string, string>::iterator> ret;
ret = map.equal_range(word);
while(ret.first != ret.second) {
vec2.push_back(ret.first->first);
getSolution(end, ret.first->second, map, vec, vec2);
vec2.pop_back();
ret.first++;
}
}
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> vec;
unordered_multimap<string, string> edges;
unordered_set<string> previousNodes;
vector<unordered_set<string> > node_levels(2);
int curLevel = 0; // an index belong to vector node_levels
node_levels[curLevel].insert(end);
unordered_set<string>::iterator it;
while(!node_levels[curLevel].empty() && node_levels[curLevel].count(start) == 0) {
for(it = node_levels[curLevel].begin(); it != node_levels[curLevel].end(); ++it) {
for(size_t i = 0; i < it->size(); ++i) {
string node(*it);
for(node[i] = 'a'; node[i] <= 'z'; ++node[i]) {
if(node == start) {
node_levels[1-curLevel].insert(node);
edges.insert(PAIR(start, *it));
break;
}
if(previousNodes.count(node) || node_levels[curLevel].count(node) || dict.count(node) == 0)
continue;
node_levels[1-curLevel].insert(node);
edges.insert(PAIR(node, *it));
}
}
previousNodes.insert(*it);
}
node_levels[curLevel].clear();
curLevel = !curLevel;
}
previousNodes.clear();
if(node_levels[curLevel].empty()) return vec;
vector<string> vec2;
getSolution(end, start, edges, vec, vec2);
return vec;
}
};

18. Word Ladder && Word Ladder II的更多相关文章

  1. Microsoft.Office.Interop.Word 创建word

    Microsoft.Office.Interop.Word 创建word 转载:http://www.cnblogs.com/chenbg2001/archive/2010/03/14/1685746 ...

  2. reverse the string word by word

    题目:Given an input string, reverse the string word by word. For example,Given s = "the sky is bl ...

  3. LeetCode 5:Given an input string, reverse the string word by word.

    problem: Given an input string, reverse the string word by word. For example: Given s = "the sk ...

  4. C#用Microsoft.Office.Interop.Word进行Word转PDF的问题

    之前用Aspose.Word进行Word转PDF发现'\'这个字符会被转换成'¥'这样的错误,没办法只能换个方法了.下面是Microsoft.Office.Interop.Word转PDF的方法: p ...

  5. [CareerCup] 18.7 Longest Word 最长的单词

    5.7 Given a list of words, write a program to find the longest word made of other words in the list. ...

  6. 17. Word Break && Word Break II

    Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...

  7. LeetCode之“动态规划”:Word Break && Word Break II

     1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...

  8. leetcode@ [139/140] Word Break & Word Break II

    https://leetcode.com/problems/word-break/ Given a string s and a dictionary of words dict, determine ...

  9. leetcode@ [79/140] Trie树应用 Word Search / Word Search II

    https://leetcode.com/problems/word-search/ class Solution { public: struct Trie{ Trie *next[]; bool ...

随机推荐

  1. HTML中head里的内容经浏览器解析后全到body里

    我从linux服务器nginx上把一个网站迁移到windows的IIS上数据什么的都么有问题,配置好rewrite以后,访问网站,发现样式变动了,网站上方空出了一块我用chrome浏览器的审查元素一看 ...

  2. MongoDB下载文件 百度盘共享

    1> mongodb下载地址: http://www.mongodb.org/downloads 官方下载不了,可以到百度共享盘里面下载 MongoDB 2.6.5 Windows 64位:   ...

  3. 拿到新机器,进行初始化和部署Nginx的过程

    1. 在/etc/ansbile/hosts中添加主机init 2. 在sysinit.yml中修改要初始化的机器:   hosts: init 3. 设置不检查key      export ANS ...

  4. 数据库对象映射为java对象,不使用框架

    方法: public static <T> List<T> processResultSetToList(ResultSet rs, Class<T> clazz) ...

  5. IE6,7 margin-bottom失效bug

    问题描述:ie6/7浏览器下,浮动元素贴近父元素的最后一行的元素(单行即指第1行)的margin-bottom值失效! 问题代码: <style type="text/css" ...

  6. .Net MVC框架 + WCF 搭建 集群开发

    http://www.cnblogs.com/zhijianliutang/archive/2012/01/28/2258844.html

  7. RABBITMQ/JAVA (主题)

    上篇博文中,我们进一步改良了日志系统.即使用Direct类型的转换器,使得接受者有能力进行选择性的接收日志,而非fanout那样,只能够无脑的转发. 虽然使用Direct类型的转换器改进了日志系统.但 ...

  8. 三部曲二(基本算法、动态规划、搜索)-1003-Lucky and Good Months by Gregorian Calendar

    模拟加阅读题......虽然很多事常识性的知识,但也有许多不知道的知识,关键是不读不知道那些是已经知道的那些不是,许多重要的信息零散的分布在一大坨英文里,读起来很痛苦......自己读了一遍,读的晕晕 ...

  9. java中的transient关键词

    以下内容全部参考自:http://www.cnblogs.com/lanxuezaipiao/p/3369962.html,有些直接复制了. 1. transient的作用 实体类实现了Seriliz ...

  10. cocos2d 保存最近登陆多个账号最多一个月

    用的是一个单例来管理 ,数据是存在本地的xml文件里的格式如下 <?xml version="1.0" encoding = "utf-8" ?> ...