126. Word Ladder II
- Total Accepted: 60804
- Total Submissions: 445894
- Difficulty: Hard
- Contributors: Admin
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 transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- Return an empty list if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
1 class Solution { 2 public: 3 vector<vector<string> > ans; 4 vector<vector<string> > findLadders(string start, string end, vector<string> &wordList) { 5 6 unordered_set<string> dict; 7 for(string s : wordList){ 8 dict.insert(s); 9 } 10 11 //dict.insert(end); 12 int dsize = dict.size(), len = start.length(); 13 unordered_map<string, vector<string> > next; 14 unordered_map<string, int> vis; 15 queue<string> q; 16 vector<string> path; 17 ans.clear(); 18 q.push(start); 19 vis[start] = 0; 20 21 22 23 while (!q.empty()) { 24 string s = q.front(); q.pop(); 25 if (s == end) break; 26 27 int step = vis[s]; 28 29 vector<string> snext; 30 31 for (int i = 0; i < len; i++) {//因为不需要记步数了 所以不要了 只用一个map来记录谁是第几步 32 string news = s; 33 for (char c = 'a'; c <= 'z'; c++) { 34 news[i] = c; 35 if (c == s[i] || dict.find(news) == dict.end()) continue; 36 auto it = vis.find(news); 37 if (it == vis.end()) {//从来没visit过的 虽然省略了q.size()的for循环,在这里也不会重复 38 q.push(news); 39 vis[news] = step + 1;//加一步 40 } 41 snext.push_back(news); 42 } 43 } 44 next[s] = snext; 45 } 46 path.push_back(start); 47 dfspath(path, next, vis, start, end); 48 return ans; 49 } 50 void dfspath(vector<string> &path, unordered_map<string, vector<string> > &next, 51 unordered_map<string, int> &vis, string now, string end){ 52 if (now == end){ 53 ans.push_back(path); //寻到了一条路径,把路径加入结果 54 //break; 55 } 56 else { 57 auto vec = next[now]; 58 int visn = vis[now]; 59 for (int i = 0; i < vec.size(); i++) {//对于每一个可能的next step进行遍历 60 if (vis[vec[i]] != visn + 1) continue; 61 path.push_back(vec[i]); 62 dfspath(path, next, vis, vec[i], end); 63 path.pop_back(); 64 } 65 } 66 } 67 };