LeetCode OJ - Word Ladder II
来源:互联网 发布:平面动画制作软件 编辑:程序博客网 时间:2024/04/28 03:47
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.
分析:一道给力的题,有人说是五星题。采用BFS遍历,并使用vector<string, vector<string> >邻接表来构建图模型,最后使用DFS深度搜索图来得到所有结果。如果遍历图有重复元素,可以使用一个标记为来记录visited。
class Solution { vector<vector<string> > ret; string END;public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { END = end; queue<string> que, next; que.push(start); dict.erase(start); unordered_set<string> del; del.insert(start); unordered_map<string, vector<string> > path; bool found = false; while(!que.empty()) { for(auto x : del) dict.erase(x); del.clear(); while(!que.empty()) { string x = que.front(); que.pop(); //根据cur查找,并push到next队列 for(int i = 0; i < x.size(); i++) { string word = x; for(char ch = 'a'; ch <= 'z'; ch++) { if(word[i] == ch) continue; word[i] = ch; //找到可达字符集合,记录到path中 if(dict.count(word)) { if(word == end) found = true; if(!del.count(word))next.push(word); del.insert(word); path[x].push_back(word); } } } } if(found) break; swap(que, next); } vector<string> item; item.push_back(start); DFS(path, start, item); return ret; }private: void DFS(unordered_map<string, vector<string> > &path, string last, vector<string> &item) { if(last == END) { ret.push_back(item); return ; } for(int i = 0; i < path[last].size(); i++) { item.push_back(path[last][i]); DFS(path, path[last][i], item); item.pop_back(); } }};
0 0
- LeetCode OJ - Word Ladder II
- LeetCode OJ Word Ladder II
- LeetCode OJ:Word Ladder
- LeetCode OJ - Word Ladder
- LeetCode OJ - Word Ladder
- LeetCode OJ Word Ladder
- 【leetcode】Word Ladder II
- [LeetCode]Word Ladder II
- [leetcode] Word Ladder II
- LeetCode - Word Ladder II
- Leetcode: Word Ladder II
- leetcode Word Ladder II
- Leetcode Word Ladder II
- LeetCode | Word Ladder II
- leetcode word ladder II
- 【Leetcode】Word Ladder II
- [LeetCode] Word Ladder II
- Word Ladder II -- LeetCode
- 链表创建
- ECC纠错算法
- 编程语言基础知识
- UVA 10427 Naughty Sleepy Boys
- WordPress修改文章列表显示摘要
- LeetCode OJ - Word Ladder II
- hdu 3033 I love sneakers!(分组背包)
- 《Lost》大结局最权威最彻底解读
- jQuery源码分析笔记--1
- ZOJ3810(2014年牡丹江网络赛B题)
- 得到地图中NPc,hero的位置
- arcSDE for Linux 安装过程中的问题
- windows下git bash显示中文
- Ubuntu 安装 mysql