LeetCode127:Word Ladder II
题目:
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
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:
解题思路:
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std; /**
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a time
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.
*/ class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> resvec;
if(start.empty() || end.empty() || dict.empty())
return resvec;
unordered_map<string, vector<string>> premap;
//这里需要用到两个vector来模拟两个队列而不是直接用两个队列,是因为需要对队列进行遍历,queue做不到
vector<string> squ[2];
squ[0].push_back(start);
bool qid = false;
bool finish = false;
while(!squ[qid].empty())
{
squ[!qid].clear();
vector<string>::iterator iter;
for(iter = squ[qid].begin(); iter != squ[qid].end(); ++iter)
dict.erase(*iter);//从dict中删除同一层的所有节点,以免造成循环操作
for(iter = squ[qid].begin(); iter != squ[qid].end(); ++iter)//处理同一层节点
{
string curstr = *iter;
for(int i = 0; i < curstr.size(); i++)
{
char t = curstr[i];
for(char j = 'a'; j <= 'z'; j++)
{
if(j == curstr[i])
continue;
curstr[i] = j;
if(curstr == end)
{
finish = true;
premap[curstr].push_back(*iter); }
else if(dict.count(curstr) > 0)
{
squ[!qid].push_back(curstr);
premap[curstr].push_back(*iter);
}
}
curstr[i] = t; }
}
if(finish)//说明已经处理到了end节点,可以直接break循环,进行结果重构了
break;
qid = !qid;//表示将要处理的下一层
}
if(premap.count(end) == 0)//表明end节点的父节点不存在,所有没有到end的转换,直接返回空resvec
return resvec;
vector<string> tmp;
getResult(resvec, tmp, premap, start, end);
return resvec;
} //DFS
void getResult(vector<vector<string> > &resvec, vector<string> &tmp,
unordered_map<string, vector<string> > &premap, string &start, string &cur)
{
tmp.push_back(cur);
if (cur == start)
{
resvec.push_back(tmp);
reverse(resvec.back().begin(), resvec.back().end());
}
else
{
vector<string> v = premap[cur];
for (int i = 0; i < v.size(); i++)
{
getResult(resvec, tmp, premap, start, v[i]);
}
}
tmp.pop_back();
}
}; int main(void)
{
string start("hit");
string end("cog");
string strarr[] = {"hot","dot","dog","lot","log"};
int n = sizeof(strarr) / sizeof(strarr[0]);
unordered_set<string> dict(strarr, strarr+n);
Solution solution;
vector<vector<string>> resvec = solution.findLadders(start, end, dict);
vector<vector<string>>::iterator iter;
for(iter = resvec.begin(); iter != resvec.end(); ++iter)
{
vector<string> tmp = *iter;
vector<string>::iterator it;
for(it = tmp.begin(); it != tmp.end(); ++it)
cout<<*it<<" ";
cout<<endl;
}
return 0;
}
以下附网上大神AC代码一份:
class Solution {
public:
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict)
{
result_.clear();
unordered_map<string, vector<string>> prevMap;
for(auto iter = dict.begin(); iter != dict.end(); ++iter)
prevMap[*iter] = vector<string>();
vector<unordered_set<string>> candidates(2);
int current = 0;
int previous = 1;
candidates[current].insert(start);
while(true)
{
current = !current;
previous = !previous;
for (auto iter = candidates[previous].begin(); iter != candidates[previous].end(); ++iter)
dict.erase(*iter);
candidates[current].clear();
for(auto iter = candidates[previous].begin(); iter != candidates[previous].end(); ++iter)
{
for(size_t pos = 0; pos < iter->size(); ++pos)
{
string word = *iter;
for(int i = 'a'; i <= 'z'; ++i)
{
if(word[pos] == i)continue;
word[pos] = i;
if(dict.count(word) > 0)
{
prevMap[word].push_back(*iter);
candidates[current].insert(word);
}
}
}
}
if (candidates[current].size() == 0)
return result_;
if (candidates[current].count(end)) break;
}
vector<string> path;
GeneratePath(prevMap, path, end);
return result_;
}
private:
void GeneratePath(unordered_map<string, vector<string>> &prevMap, vector<string>& path, const string& word)
{
if (prevMap[word].size() == 0)
{
path.push_back(word);
vector<string> curPath = path;
reverse(curPath.begin(), curPath.end());
result_.push_back(curPath);
path.pop_back();
return;
}
path.push_back(word);
for (auto iter = prevMap[word].begin(); iter != prevMap[word].end(); ++iter)
GeneratePath(prevMap, path, *iter);
path.pop_back();
}
vector<vector<string>> result_;
};
代码来源:http://blog.csdn.net/doc_sgl/article/details/13341405
LeetCode127:Word Ladder II的更多相关文章
- 18. Word Ladder && Word Ladder II
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
- 126. Word Ladder II(hard)
126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- [LeetCode] 126. Word Ladder II 词语阶梯之二
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
随机推荐
- 读Java 804 - Quick refresher
Upcast永远是成功的,但Downcast不是,记得做instanceof判断 仅抛不同异常,而返回值相同的重载是不可以的 static import只会import静态类 static metho ...
- 64位Linux下编译搭建Nginx1.5与PHP5.5(CentOS6.4)
(1)安装Nginx1.5.2更新Nginx和PHP的依赖包yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng \libp ...
- Swift 关键字汇总
常见的关键字有以下4种 与声明有关的关键字:class.deinit.enum.extension.func.import.init.let.protocol.static.struct.subscr ...
- Windows下Git安装指南
参考<Git权威指南>安装整理,图书配套网址参见[1] 1. Cygwin下安装配置Git 1. 在Windows下安装配置Git有2种不同的方案 (1)msysGit, (2)Cygwi ...
- EvreryDay Collect
1.在使用WebService时我们经常会考虑以下问题:怎么防止别人访问我的WebService? 在System.Net中提供了一个NetworkCredential,只有获得该凭证的用户才能访问相 ...
- ImageSource的使用
很多时候,我们会使用图片来装饰UI,比如作为控件背景等.而这些图片可以分为两种形式,即存在于本地文件系统中的图片和存在于内存中的图片对于这两种形式的图片,在WPF中,使用方法不同,下面主要说明针对这两 ...
- 发布FTP服务,防火墙配置
最近需要在Web服务器上发布一下FTP,不想安装Server-U之类的,就用IIS的了,安装好后,发现外网无法连接.经过测试,发现是防火墙的问题. 查找了下关于FTP的资料,ftp server支持两 ...
- 理解RxJava:(一)基础知识
理解RxJava:(一)基础知识 本文翻译自Grokking RxJava, Part 1: The Basics,著作权归原作者danlew所有.译文由JohnTsai翻译.转载请注明出处,并保留此 ...
- php随机密码函数的实例代码
php随机密码函数的入门例子 时间:2015-12-16 20:42:48来源:网络 导读:php生成随机密码的函数实例,php生成随机密码的函数,生成数字.大小写字母与特殊字符组合的随机密码. ...
- Android UI 优化——使用HierarchyViewer工具
先说些题外话,希望路过的各位支持,博主有幸成为2013年度博客之星的候选人,期待你的一票,谢谢. 投票猛击: http://vote.blog.csdn.net/blogstaritem/blogst ...