[LeetCode]Word Ladder II
2016-04-17 19:06
459 查看
Word Ladder II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord,such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord =
"hit"
endWord =
"cog"
wordList =
["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: //利用BFS构建图,然后利用DFS深度搜索解 vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) { unordered_set<string> current_step; unordered_set<string> next_step; unordered_map<string,unordered_set<string>> Graph; unordered_set<string> unvisited = wordList; current_step.insert(beginWord); unvisited.erase(beginWord); //每次删除一层的结构,同一层出现可能出现相同解要记住,所以每次只能一层层的删除 while(current_step.count(endWord)==0 && unvisited.size()>0){ for(auto pcu = current_step.begin(); pcu!=current_step.end(); pcu++){ string word = *pcu; for(int i=0; i<beginWord.length(); ++i) for(int j=0; j<26; ++j){ string temp = word; if(temp[i] == 'a'+j) continue; temp[i] = 'a'+j; if(unvisited.count(temp)>0){ next_step.insert(temp); Graph[word].insert(temp); } } } if(next_step.empty()) break; for(auto it = next_step.begin(); it!=next_step.end(); ++it){ unvisited.erase(*it); } current_step = next_step; next_step.clear(); } vector<vector<string>> ret; vector<string> path; DFS(Graph,beginWord,endWord,path,ret); return ret; } void DFS(unordered_map<string,unordered_set<string>> &Graph,string beginWord,string endWord,vector<string> &path,vector<vector<string>> &ret){ path.push_back(beginWord); if(beginWord == endWord){ //reverse(path.begin(),path.end()); ret.push_back(path); } unordered_set<string> adj = Graph[beginWord]; for(auto i=adj.begin(); i!=adj.end(); ++i){ DFS(Graph,*i,endWord,path,ret); path.pop_back(); } } };
相关文章推荐
- AMS PMS WMS等简单介绍
- Struts2中基于OGNL的类型转换
- 辨析:成员变量、局部变量以及静态变量
- linux 安装svn(二)创建版本库
- 论自作音乐播放器涉及知识点总结
- install Hadoop
- 关于ios中的setNeedsDisplay和setNeedsLayout
- 程序编译链接运行深入剖析
- 《Javascript秘密花园》学习笔记(下)
- 进程与线程的一个简单解释
- poj 3041(最大匹配问题)
- Android横竖屏切换继续播放视频
- scala知识点(二)
- linux及安全第八周总结
- 集合中泛型正确地擦除
- Android 6.0运行时权限小结
- ScheduledExecutorService定时周期执行指定的任务
- php中获得数组长度的方法
- wxWidgets教程(3)- 窗口、对话框与控件
- 数据挖掘十大经典算法