797. 所有可能的路径

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

二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。

译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution {

    private List<List<Integer>> ret = new ArrayList<>();

    private LinkedList<Integer> path = new LinkedList<>();

    private int[][] graph;

    private void solve(int from) {
        if (from == graph.length - 1) {
            ret.add(new ArrayList<>(path));
            return;
        }

        for (int to : graph[from]) {
            path.offerLast(to);
            solve(to);
            path.pollLast();
        }
    }

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        this.graph = graph;
        this.path.offerLast(0);
        solve(0);
        return ret;
    }
}
posted @ 2021-12-21 11:02  Tianyiya  阅读(44)  评论(0)    收藏  举报