LeetCode-所有路径

320 阅读1分钟

算法记录

LeetCode 题目:

  给定一个有 n 个节点的有向无环图,用二维数组 graph 表示,请找到所有从 0 到 n-1 的路径并输出(不要求按顺序)。


说明

一、题目

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

二、分析

  • 题目明确不存在回环,也就是说一条路径深度遍历肯定能走到尽头,如果尽头是终点,那么就可以置入结果集中,否则将永远不会到达终点,直接丢掉即可。
  • 需要注意的是一个边界的判断,如果说矩阵本来就为空,那么起点也就是终点,需要进行添加。
class Solution {
    private List<List<Integer>> ret; 
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        ret = new ArrayList();
        List<Integer> temp = new ArrayList();
        temp.add(0);
        if(graph[0].length == 0) {
            ret.add(temp);
        }
        dfs(graph, 0, temp, graph.length - 1);
        return ret; 
    }
    public void dfs(int[][] graph, int deep, List<Integer> temp, int max) {
        if(graph[deep].length == 0) return;
        for(int i = 0; i < graph[deep].length; i++) {
            temp.add(graph[deep][i]);
            if(graph[deep][i] == max) ret.add(new ArrayList(temp));
            else dfs(graph, graph[deep][i], temp, max);
            temp.remove(temp.size() - 1);
        }
    }
}

总结

熟悉深度优先遍历的方式。