给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。
示例:
输入: [[1,2], [3], [3], []]
输出: [[0,1,3],[0,2,3]]
解释: 图是这样的:
0--->1
| |
v v
2--->3
这有两条路: 0 -> 1 -> 3 和 0 -> 2 -> 3.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
vector<vector<int>> ans;
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<int> path;
path.push_back(0);
dfs(graph,0,path);
return ans;
}
void dfs(vector<vector<int>> &graph, int i, vector<int> path)
{
if(i == graph.size()-1)
{
ans.push_back(path);
return;
}
for(int idx = 0; idx < graph[i].size(); idx++)
{
path.push_back(graph[i][idx]);
dfs(graph, graph[i][idx], path);
path.pop_back();
}
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有