有向无环图-dfs-797所有可能的路径

给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)

graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。

示例 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]]
提示:

n == graph.length
2 <= n <= 15
0 <= graph[i][j] < n
graph[i][j] != i(即不存在自环)
graph[i] 中的所有元素 互不相同
保证输入为 有向无环图(DAG)
Related Topics

👍 409, 👎 0bug 反馈 | 使用指南 | 更多配套插件
通知:数据结构精品课 已更新到 V2.1,手把手刷二叉树系列课程 上线,第 20 期打卡挑战 即将开始,最后 1 天报名!

⭐️labuladong 题解

labuladong 思路
基本思路
本文有视频版:图论基础及遍历算法

解法很简单,以 0 为起点遍历图,同时记录遍历过的路径,当遍历到终点时将路径记录下来即可。

既然输入的图是无环的,我们就不需要 visited 数组辅助了,可以直接套用 图的遍历框架。

详细题解:图论基础及遍历算法

标签:图论算法,数据结构

思路:dfs回溯


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    // 记录所有路径

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> resList = new LinkedList<>();
        dfs(resList, new ArrayList(), graph, 0, graph.length);
        return resList;
    }

    /* 图的遍历框架 */
    void dfs(List<List<Integer>> resList, ArrayList<Integer> res, int[][] graph, int i, int n) {
        if (i == n - 1) {
            res.add(i);
            resList.add(new ArrayList<>(res));
            res.remove(res.size() - 1);
            return;
        }

        res.add(i);
        for (int next : graph[i]) {
            dfs(resList, res, graph, next, n);
        }

        res.remove(res.size() - 1);

    }
}

//leetcode submit region end(Prohibit modification and deletion)

posted @   小傻孩丶儿  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示