leetcode126 Word Ladder II
Posted 王宜鸣
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode126 Word Ladder II相关的知识,希望对你有一定的参考价值。
思路:
宽搜过程中分层记录路径,递归还原。
实现:
1 class Solution 2 { 3 public: 4 void getPath(string now, string beginWord, string endWord, vector<string>& buf, unordered_map<string, unordered_set<string>>& par, vector<vector<string>>& ret) 5 { 6 if (now == beginWord) 7 { 8 vector<string> tmp(1, endWord); 9 for (auto it : buf) tmp.push_back(it); 10 ret.push_back(tmp); 11 reverse(ret.back().begin(), ret.back().end()); 12 return; 13 } 14 for (auto it : par[now]) 15 { 16 buf.push_back(it); 17 getPath(it, beginWord, endWord, buf, par, ret); 18 buf.pop_back(); 19 } 20 } 21 vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) 22 { 23 unordered_set<string> tmp; 24 for (auto it : wordList) tmp.insert(it); 25 unordered_map<string, unordered_set<string>> par; 26 unordered_set<string> q; 27 q.insert(beginWord); 28 bool flg = false; 29 while (!q.empty()) 30 { 31 unordered_set<string> next; 32 for (auto it : q) 33 { 34 for (int i = 0; i < it.length(); i++) 35 { 36 for (char c = ‘a‘; c <= ‘z‘; c++) 37 { 38 string buf = it; 39 if (buf[i] == c) continue; 40 buf[i] = c; 41 if (!tmp.count(buf)) continue; 42 if (!q.count(buf)) 43 { 44 next.insert(buf); 45 par[buf].insert(it); 46 } 47 if (buf == endWord) flg = true; 48 } 49 } 50 } 51 for (auto it : q) { tmp.erase(it); } 52 q = next; 53 if (flg) break; 54 } 55 vector<vector<string>> ret; 56 if (flg) 57 { 58 vector<string> buf; 59 getPath(endWord, beginWord, endWord, buf, par, ret); 60 } 61 return ret; 62 } 63 };
以上是关于leetcode126 Word Ladder II的主要内容,如果未能解决你的问题,请参考以下文章