LeetCode:所有可能的路径(深度优先搜索/广度优先搜索)

 题目描述:

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

二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a )空就是没有下一个结点了。

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

 解题:

1.深度优先搜索

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) { 
        List<List<Integer>> paths = new ArrayList<>();
        if (graph == null || graph.length == 0) {
            return paths;
        }

        dfs(graph, 0, new ArrayList<>(), paths);  //深度优先搜索
        return paths;
    }
    public void dfs(int[][] graph, int node, List<Integer> path, List<List<Integer>> paths){
        path.add(node);  //入栈(List)
        if(node == graph.length-1){    //如果已经走到头
            paths.add(new ArrayList<>(path));   //将栈(List)中的元素添加进paths
            return;
        }
        for(int nextNode: graph[node]){
            dfs(graph, nextNode, path, paths);   //递归调用
            path.remove(path.size()-1);    //出栈(List)
        }
    }
}

 2.广度优先搜索

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> paths = new ArrayList<>();
        if (graph == null || graph.length == 0) {
            return paths;
        }

        Queue<List<Integer>> queue = new LinkedList<>();
        List<Integer> path = new ArrayList<>();
        path.add(0);
        queue.add(path);

        while ( queue.size() > 0 ) {
            int levelSize = queue.size();  
            List<Integer> currentPath = queue.poll();  //当前路径出队列
            int node = currentPath.get(currentPath.size() - 1);  
            for (int nextNode: graph[node]) {  //遍历当前路径的下一个节点
                List<Integer> tmpPath = new ArrayList<>(currentPath);
                tmpPath.add(nextNode);   //将下一个节点并入当前路径
                if (nextNode == graph.length - 1) {    //如果走到头了
                    paths.add(new ArrayList<>(tmpPath));    //将该条路径加入paths
                } else {
                    queue.add(new ArrayList<>(tmpPath));    //将新路径入队列
                } 
            }
        }
        return paths;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值