797. All Paths From Source to Target的C++解法
阿新 • • 發佈:2018-12-09
相當於圖的深度優先遍歷和廣度優先遍歷。我AC的程式碼是深度優先的。要注意的是,因為用了一個全域性變數path記錄當前路徑,所以回退的時候要手動pop一下。
class Solution { public: vector<vector<int>> res; vector<int> path; vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { int n = graph.size()-1; tryaroad(0, n, graph); return res; } void tryaroad(int f, int r, vector<vector<int>>& graph) { if (f == r) { path.push_back(r); res.push_back(path); } else { path.push_back(f); for (int i = 0; i < graph[f].size(); i++) { tryaroad(graph[f][i], r, graph); path.pop_back(); } } } };
速度比較慢,但是看到一個beat100%的跟我寫得差不多,唯一的不同是把res和path放在了實參列表裡傳遞:
class Solution { public: vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<vector<int>> rt; vector<int> vc={0}; dfs( vc, rt, graph); return rt; } void dfs( vector<int>& vc, vector<vector<int>>& rt, vector<vector<int>>& graph) { if(vc.back()==graph.size()-1) { rt.push_back(vc); return ; } for( int j=0; j<graph[vc.back()].size(); j++) { vc.push_back(graph[vc.back()][j]); dfs( vc, rt, graph); vc.pop_back(); } return ; } };
BFS的不太好寫,還沒找到寫得比較好的。