Leetcode#126 Word Ladder II
既然是求最短路径,可以考虑动归或广搜。这道题对字典直接进行动归是不现实的,因为字典里的单词非常多。只能选择广搜了。
思路也非常直观,从start或end开始,不断加入所有可到达的单词,直到最终到达另一端。本质上广度优先遍历图。
需要注意的是,拓展下一个单词时不能对字典进行枚举,因为字典里的单词太多。幸好单词本身都不长,所以直接枚举单词所有可能的变形,看看在dict中出现没有。
当然还不止这些,上面的做法仍然会超时,需要添加剪枝策略:
1. 如果某个单词在以前遍历过了,那么以后都不用再考虑,因为之后遍历到的路径一定不是最短的
2. 在广搜法拓展下一轮单词时,注意去重
此外还需要注意的是,不能把每个单词到start或end的路径都保存下来,那样内存会爆掉。所以要压缩保存结果,通常的做法是用一个map保存当前单词下一步是什么单词。例如next[word] = {next_word1, next_word2, next_word3...}。最后从next[start]开始再次使用广度优先搜索法构造出所有解。
算法不难,但是编码非常容易出错,所以总体上还是挺难的。最后运行时间640ms,还是有挺大优化空间的。
代码写的有些啰嗦,DFS不一定要用队列(我还是用了队列),这道题用unordered_set更好,不需要用额外的数据结构去重了。
代码:
bool adjacentp(string &a, string &b) {
for (int i = a.length() - , d = ; i >= ; i--) {
d += a[i] != b[i] ? : ;
if (d > )
return false;
}
return true;
}
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {
map<string, set<string> > next;
unordered_set<string> covered; // 当前已经访问过的单词
queue<string> que;
bool found = false; // 是否已经找到
next[end] = set<string>();
covered.insert(end);
que.push(end);
while (!que.empty() && !found) {
unordered_set<string> rset;
queue<string> rque;
while (!que.empty()) {
string curr = que.front();
que.pop();
if (adjacentp(curr, start)) {
found = true;
next[start].insert(curr);
continue;
}
for (int i = curr.length() - ; i >= ; i--) {
for (int j = ; j < ; j++) {
string prev = curr;
prev[i] = 'a' + j;
// 如果prev之前没有被访问过,且字典里有这个单词
if (covered.find(prev) == covered.end() && dict.find(prev) != dict.end()) {
next[prev].insert(curr);
// 如果在DFS的本轮拓展中还没有访问过该节点,则加入下一轮的拓展节点中
if (rset.find(prev) == rset.end()) {
rset.insert(prev);
rque.push(prev);
}
}
}
}
}
que = rque;
for (auto w : rset) {
covered.insert(w);
}
}
queue<vector<string> > laddersQue;
vector<vector<string> > ladders;
laddersQue.push(vector<string>(, start));
while (!laddersQue.empty()) {
vector<string> ladder = laddersQue.front();
laddersQue.pop();
if (ladder.back() == end)
ladders.push_back(ladder);
else {
for (auto s : next[ladder.back()]) {
vector<string> newLadder = ladder;
newLadder.push_back(s);
laddersQue.push(newLadder);
}
}
}
return ladders;
}
Leetcode#126 Word Ladder II的更多相关文章
- Java for LeetCode 126 Word Ladder II 【HARD】
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- [LeetCode] 126. Word Ladder II 词语阶梯 II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...
- [LeetCode] 126. Word Ladder II 词语阶梯之二
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- leetcode 126. Word Ladder II ----- java
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- leetcode@ [126] Word Ladder II (BFS + 层次遍历 + DFS)
https://leetcode.com/problems/word-ladder-ii/ Given two words (beginWord and endWord), and a diction ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
- 126. Word Ladder II(hard)
126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
随机推荐
- 多端口站点设置,以APMSERV集成环境为例!
以下以APMSERV集成环境为例: 1.找到你的apache上的配置文件httpd.conf,用记事本打开, D:\APMServ\Apache\conf 2.修改以下几项: Listen 80 下增 ...
- php中empty(), is_null(), isset()函数区别
empty(), is_null(), isset()真值表(区别) 我们先来看看这3个函数的功能描述 www.111cn.net isset 判断变量是否已存在,如果变量存在则返回 TRUE,否则返 ...
- 关于FragmentManager findFragmentById 返回nul
先看Fragment的两种生成方式 一.用xml标签生成 在fragment的宿主activity中添加xml标签 <fragment android:id="@+id/fragmen ...
- python爬虫-urllib模块
urllib 模块是一个高级的 web 交流库,其核心功能就是模仿web浏览器等客户端,去请求相应的资源,并返回一个类文件对象.urllib 支持各种 web 协议,例如:HTTP.FTP.Gophe ...
- Python脚本控制的WebDriver 常用操作 <六> 打印当前页面的title及url
下面将使用WebDriver来答应浏览器页面的title和访问的地址信息 测试用例场景 测试中,访问1个页面然后判断其title是否符合预期是很常见的1个用例: 假设1个页面的title应该是'hel ...
- C#判断ip地址是否ping的通
Ping pingSender = new Ping(); PingReply reply = pingSender.Send("127.0.0.1",120);//第一个参数为i ...
- .NET开源工作流RoadFlow-流程设计-流程属性设置
打开流程设计器点击新建流程后会弹出新流程属性设置框,属性设置包括基本信息,数据连接和标识字段三项设置. 1.基本信息 流程ID:系统自动给每个流程分配的一个唯一ID. 流程名称:给您的新流程取一个名称 ...
- 历时八年,HTML5 标准终于完工了
万维网联盟(W3C)2014年10月29日泪流满面地宣布,经过几乎8年的艰辛努力,HTML5标准规范终于最终制定完成了,并已公开发布. 在此之前的几年时间里,已经有很多开发者陆续使用了HTML5的部分 ...
- Paragon NTFS for Mac免费获取官方赠送正版.更新获取ntfs for mac 14方法
Paragon NTFS for Mac免费获取官方赠送正版,没有这个软件的朋友赶紧收下.获取地址http://www.paragon-drivers.com/cn/ntfs-mac-free/ntf ...
- mac os x 系统安装 genymotion android 模拟器
如果你有 apk 文件 想 运行一下看看 ,但是又没有 android 设备 ,那么 genymotion 将会是一个 很好的解决方案. 1.安装 下载链接: https://cloud.geny ...