思路:
宽搜过程中分层记录路径,递归还原。
实现:
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 };
时间: 2024-10-17 22:45:41