美文网首页
LeetCode 第797题: 所有可能的路径

LeetCode 第797题: 所有可能的路径

作者: 放开那个BUG | 来源:发表于2021-05-02 16:42 被阅读0次

1、前言

题目描述

2、思路

这题的表示形式类似于图的领接表的表示方法,数组里存储相邻的节点。

这一题并没有说出现环的情况,且需要求的是遍历过程的路径,所以解法类似于回溯的解法,只不过回溯是遍历树,这边是遍历图。但是树其实也算图,所以他们遍历节点的方式非常类似。

3、代码

public class AllPathsSourceTarget {

    List<List<Integer>> res = new LinkedList<>();

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        dfs(graph, 0, new LinkedList<>());
        return res;
    }

    private void dfs(int[][] graph, int value, LinkedList<Integer> path) {
        path.add(value);

        int n = graph.length;
        if(value == n - 1){
            res.add(new LinkedList<>(path));
            path.removeLast();
            return;
        }

        for (int i : graph[value]) {
            dfs(graph, i, path);
        }

        path.removeLast();
    }

    public static void main(String[] args) {
        int[][] graph = {{1, 2}, {3}, {3}, {}};
        List<List<Integer>> paths = new AllPathsSourceTarget().allPathsSourceTarget(graph);
        for (List<Integer> path : paths) {
            for (Integer integer : path) {
                System.out.print(integer + "   ");
            }
            System.out.println();
        }
    }
}

相关文章

网友评论

      本文标题:LeetCode 第797题: 所有可能的路径

      本文链接:https://www.haomeiwen.com/subject/hrcvlltx.html