首页 > 其他 > 详细

2021-8-25 All Paths From Source to Target

时间:2021-08-26 09:13:46      阅读:19      评论:0      收藏:0      [点我收藏+]

难度 中等

题目 Leetcode:

All Paths From Source to Target

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

 

题目解析

本题用到了很基础的dfs,可以说是模板题了。

所以具体的直接看代码的注释吧

 1 class Solution {
 2 public:
 3     vector<vector<int>> ans;
 4     vector<int> temp;
 5     void dfs(vector<vector<int>>& a, int x, int n) 
 6     {
 7         if (x == n) //如果当前节点到达目标节点,那么把当前路径记录到ans容器种并返回
 8         {
 9             ans.push_back(temp);
10             return;
11         }
12         for (auto& y : a[x]) //遍历当前节点的目的地
13         {
14             temp.push_back(y);
15             dfs(a, y, n);
16             temp.pop_back();
17         }
18     }
19     vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
20         temp.push_back(0);//从0开始
21         int des=graph.size()-1;
22         dfs(graph, 0,des);//数组 当前节点 目标节点
23         return ans;
24     }
25 };

 

2021-8-25 All Paths From Source to Target

原文:https://www.cnblogs.com/lovetianyi/p/15187274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!