lintcode:Word Ladder II
来源:互联网 发布:淘宝充值平台押金 编辑:程序博客网 时间:2024/06/04 19:21
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
参考:http://www.cnblogs.com/x1957/p/3526838.html
1.依然是BFS,记录每个的前驱节点father[x],当然这个father有多个;
采用分层遍历,只要到了end,那么这一层所有的都是最短的,一样长。
2.然后用DFS遍历father,从end到start
DFS递归完注意‘恢复现场’。
class Solution {public: /** * @param start, a string * @param end, a string * @param dict, a set of string * @return a list of lists of string */ void dfs(vector<vector<string>> &res,unordered_map<string,vector<string>> &father, vector<string> &path,string &start,string &end){ path.push_back(end); if(end==start){ vector<string> tmp(path); reverse(tmp.begin(),tmp.end()); res.push_back(tmp); path.pop_back(); return; } vector<string> fa=father[end]; for(int i=0;i<fa.size();i++){ string f=fa[i]; dfs(res,father,path,start,f); } path.pop_back(); } vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { // write your code here vector<vector<string>> res; /*这里需要用set而不能用vector,会使得得到相同的最短路径*/ unordered_set<string> current,next; unordered_set<string> visited; unordered_map<string,vector<string>> father; current.insert(start); bool found=false; while (!current.empty() && !found){ for(string str:current){ visited.insert(str); } for (string front:current){ for (int i = 0; i < front.size(); i++){ for (int ch = 'a'; ch <= 'z'; ch++){ if(front[i]==ch) continue; string tmp = front; tmp[i] = ch; if (tmp == end){ found=true; } if (dict.find(tmp)!=dict.end() && visited.find(tmp)==visited.end() ){ father[tmp].push_back(front); next.insert(tmp); } } } } current.clear(); swap(current,next); } if(found){ vector<string> path; dfs(res,father,path,start,end); } return res; }};
0 0
- lintcode:Word Ladder II
- Word Ladder/ Word Ladder II
- lintcode: Word Ladder
- Word Ladder II
- Word Ladder II
- 【leetcode】Word Ladder II
- [LeetCode]Word Ladder II
- Word Ladder II
- [leetcode] Word Ladder II
- LeetCode - Word Ladder II
- Word Ladder II
- Leetcode: Word Ladder II
- leetcode Word Ladder II
- Leetcode Word Ladder II
- LeetCode | Word Ladder II
- Word Ladder II
- Word Ladder II
- Word Ladder II
- 修改/etc/resolv.conf又恢复到原来的状态?
- [转载]基于Matlab的标记分水岭分割算法
- VIM 高效操作
- UVA_10422_Knights in FEN
- 在CentOS 7上构建RAID5、LVM和SAMBA服务器(4)——逻辑卷(组)扩容
- lintcode:Word Ladder II
- 《JAVA并发编程实践》学习笔记(第六.七章)
- FMDB 操作数据库
- 需求分析
- handle机制
- 循序渐进之Spring AOP(2) - 基本概念
- Mybatis入门配置及基本查询
- FMDB简介
- 全国首堂沉浸式教学系统实验课开启了虚拟现实教育的新纪元