首页 > 其他 > 详细

797. All Paths From Source to Target

时间:2021-04-17 10:44:26      阅读:13      评论:0      收藏:0      [点我收藏+]

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]).

 

Example 1:

技术分享图片

Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

Constraints:

  • n == graph.length
  • 2 <= n <= 15
  • 0 <= graph[i][j] < n
  • graph[i][j] != i (i.e., there will be no self-loops).
  • The input graph is guaranteed to be a DAG.

//from huahua

 

  • class Solution {
    public:
        vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
            vector<vector<int>> ans;
            vector<int> path(1,0); //定义长度为1,初始值为0的数组path
            dfs(graph,0,graph.size()-1,path,ans);
            return ans;
        }
    private:
        void dfs( vector<vector<int>>& graph,int cur,int dest,vector<int> &path,vector<vector<int>>& ans){
            if(cur==dest){
                ans.push_back(path);
                return;
            }
            for(int next:graph[cur]){
                path.push_back(next);
                dfs(graph,next,dest,path,ans);
                path.pop_back(); //删除path数组中最后一个元素
            }
        }
        
    };

     

797. All Paths From Source to Target

原文:https://www.cnblogs.com/Makerr/p/14668802.html

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