题目描述
题目链接:leetcode 797. 所有可能的路径
给一个有 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]]
分析
直接dfs搜索路径即可。搜到终点时,就把路径添加到答案中。
C++代码
class Solution {
public:
void dfs(vector<vector<int>>& graph,vector<vector<int>>& res,vector<int>path,int u,int t){
path.push_back(u); //把当前点添加到路径中
if(u==t) //搜到终点时,把路径添加到答案中
{
res.push_back(path);
}
//搜索u的出边
for(int i=0;i<graph[u].size();i++)
{
int v=graph[u][i];
dfs(graph,res,path,v,t);
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>>res;
vector<int>path;
int t=graph.size()-1;
dfs(graph,res,path,0,t);
return res;
}
};