leetcode上通過率最低的了...
不只要找最短路,還要記錄路徑
每次遇到記錄路徑的感覺都好麻煩TT,不太喜歡記錄路徑...
依然是BFS,記錄每個的前驅節點father[x],當然這個father有多個
還有個問題就是...如果BFS的話到end肯定有很多路徑,那最短的是啥呢?
所以我們采用分層遍歷,只要到了end,那么這一層所有的都是最短的(一樣長
然后用DFS遍歷father,從end到start
注意就是DFS在恢復狀態的時候一定要考慮完,我之前就是在前面return了但是后面才是恢復狀態,導致錯誤
class Solution { public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string> >ans; if(start == end) return ans; unordered_set<string>current , next; unordered_set<string> flag; unordered_map<string,vector<string> > father; current.insert(start); bool found = false; while(!current.empty() && !found) { //expand for(const auto &x : current) { flag.insert(x); } for(auto x : current) { for(int i = 0 ; i < x.size() ; ++i) { for(int j = 'a' ; j <= 'z' ; ++j) { if(x[i] == j) continue; string tmp = x; tmp[i] = j; if(tmp == end) found = true; if(dict.find(tmp) != dict.end() && flag.find(tmp) == flag.end()) { next.insert(tmp); father[tmp].push_back(x); } } } } //end expand current.clear(); swap(current, next); } //start foudn father if(found) { vector<string> c; dfs(ans , father , c , start , end); } return ans; } private: void dfs(vector<vector<string> >&ans, unordered_map<string,vector<string> >& father , vector<string>& c , string& start , string& now) { c.push_back(now); if(now == start) { ans.push_back(c); reverse(ans.back().begin() , ans.back().end()); c.pop_back(); return; } auto que = father.find(now) -> second; for(auto& x : que) { dfs(ans , father , c , start , x); } c.pop_back(); } };