[LeetCode]Word Ladder II
来源:互联网 发布:网络出版许可证 查询 编辑:程序博客网 时间:2024/05/21 22:43
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(); } }};
0 0
- 【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
- Leetcode: Word Ladder II
- leetcode-Word Ladder II
- leetcode-Word Ladder II
- leetcode: Word Ladder II
- leetcode Word Ladder II
- Leetcode: Word Ladder II
- 关于ios中的setNeedsDisplay和setNeedsLayout
- 梯度下降
- 进程与线程的一个简单解释
- 《Javascript秘密花园》学习笔记(下)
- AMS PMS WMS等简单介绍
- [LeetCode]Word Ladder II
- 数据结构—KMP模板
- Struts2中基于OGNL的类型转换
- 一、选择排序
- 动态加入Sprite
- 辨析:成员变量、局部变量以及静态变量
- SQL Server 事务的使用
- php面试题之一——HTML+CSS(基础部分)
- 自考路之百尺竿头须进步