ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-07-15 11:01:18  阅读:175  来源: 互联网

标签:paths 优先 int graph List 搜索 path new 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;
    }
}

标签:paths,优先,int,graph,List,搜索,path,new,LeetCode
来源: https://blog.csdn.net/qq_36733726/article/details/118753646

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有