题目:
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点,空就是没有下一个结点了。
题目链接:All Paths From Source to Target
C++:
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void dfs(vector<vector<int>>& graph, int node, int e) {
if(e == node) {
res.push_back(path);
return ;
}
for(int i = 0; i < graph[node].size(); i++) {
path.push_back(graph[node][i]);
dfs(graph, graph[node][i], e);
path.pop_back();
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
int end = graph.size() - 1;
path.push_back(0);
dfs(graph, 0, end);
return res;
}
};