题目描述:
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a )空就是没有下一个结点了。
示例 1:
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例 2:
输入:graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
示例 3:
输入:graph = [[1],[]]
输出:[[0,1]]
示例 4:
输入:graph = [[1,2,3],[2],[3],[]]
输出:[[0,1,2,3],[0,2,3],[0,3]]
示例 5:
输入:graph = [[1,3],[2],[3],[]]
输出:[[0,1,2,3],[0,3]]
提示:
结点的数量会在范围 [2, 15] 内。
你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。
方法1:
主要思路:解题汇总链接
(1)直接dfs搜索出每条路径,存储到对应的结果中;
class Solution {
public:
void dfs(vector<vector<int>>&graph,vector<int>&path,vector<vector<int>>&res,const int&end,int index){
if(index==end){//路径到的终止位置
res.push_back(path);//压入当前路径
res.back().push_back(end);//压入最后一个结点
return;
}
path.push_back(index);//压入当前结点
for(int&i:graph[index]){//遍历当前结点可以到达的结点
dfs(graph,path,res,end,i);
}
path.pop_back();//回溯
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> res;//存储所有路径
vector<int> path;//存储当前路径
int end=graph.size()-1;//路径的终止位置
dfs(graph,path,res,end,0);
return res;
}
};