题目链接:https://leetcode.com/problems/all-paths-from-source-to-target/description/
解题思路:dfs+回溯
从0开始,通过bfs搜索并回收路径上的答案,如果到终点的话,回收答案即可。
AC(Accept)代码:
class Solution {
public:
int m;
vector<vector<int>>ans;
vector<int>pushans;
vector<bool>vis;
vector<vector<int>>Map;
void dfs(vector<vector<int>>& graph, int now){
if(now==m-1){
pushans.push_back(m-1);
ans.push_back(pushans);
// pushans.pop_back();
return;
}
vis[now]= true;
pushans.push_back(now);
for(int i=0;i<m;i++){
if(graph[now][i]&&!vis[i]){
dfs(graph, i);
vis[i]=false;
pushans.pop_back();
}
}
vis[now]=false;
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
m=graph.size();
vector<int>tmp(m, 0);
Map.resize(m, tmp);
for(int i=0;i<graph.size();i++){
for(int j=0;j<graph[i].size();j++){
if(graph[i][j]){
Map[i][graph[i][j]]=1;
}
}
}
// for(int i=0;i<m;i++){
// for(int j=0;j<m;j++){
// cout<<Map[i][j]<<" ";
// }
// cout<<endl;
// }
vis.resize(m, false);
dfs(Map, 0);
return ans;
}
};