leetcode-797. 所有可能的路径(BFS、DFS)

797. 所有可能的路径(BFS、DFS)

题目

给你一个有 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)
分析

方法一:由于本题是有向无环。可以采用广度优先遍历,搜索所有0到n-1的路径。

**方法二:**采用深度优先遍历,搜索所有0到n-1的路径。

代码
class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> result = new ArrayList<>();
        List<List<Integer>> paths = new ArrayList<>();
        paths.add(new ArrayList<>(Arrays.asList(0)));
        List<Integer> cur = new ArrayList<>();
        int index;
        while(paths.size()>0){
            cur = paths.remove(0);
            index = cur.get(cur.size()-1);
            for(int i=0;i<graph[index].length;i++){
                List<Integer> temp = new ArrayList<>(cur);
                temp.add(graph[index][i]);
                if(graph[index][i]==graph.length-1) result.add(temp);
                else paths.add(temp);
            }
        }
        return result;
    }
}
class Solution {
    public List<List<Integer>> result = new ArrayList<>();
    public List<Integer> path = new ArrayList<>(Arrays.asList(0));
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        dfs(graph, 0);
        return result;
    }

    public void dfs(int[][] graph, int index){
        if(index==graph.length-1){
            result.add(new ArrayList<>(path));
            return;
        }
        for(int i=0;i<graph[index].length;i++){
            path.add(graph[index][i]);
            dfs(graph, graph[index][i]);
            path.remove(path.size()-1);
        }
    }
}
结果

时间超过100%

内存超过40%

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值