797. 所有可能的路径

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

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

/*
    一个典型的搜索案例,深度搜索,即一条路走到黑,不通再返回上一个节点寻找新路。不停的尝试和反馈的过程。

*/
class Solution {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    Deque<Integer> df = new ArrayDeque<Integer>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        df.offerLast(0);
        dfs(graph,0,graph.length - 1);
        return ans;
    }

    public void dfs(int[][] graph, int a, int n){
        if(a == n){
            ans.add(new ArrayList<Integer>(df));
            return;
        }
        for(int y:graph[a]){
            df.offerLast(y);
            dfs(graph,y,n);
            df.pollLast();
        }
    }
}
/*
    BFS:将一个节点的所有情况都遍历一遍,存放在栈中。放入记录放入纪律,扩散。
*/
class Solution {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    Queue<List<Integer>> df = new LinkedList<>();

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        df.add(new ArrayList<>(){{add(0);}});
        while(!df.isEmpty()){
            List<Integer> path = df.remove();
            int node = path.get(path.size() - 1);
            if(node == graph.length - 1){
                ans.add(path);
                continue;
            }
            for(int y:graph[node]){
                List<Integer> y_path = new ArrayList<>(path);
                y_path.add(y);
                df.add(y_path);
            }
            
        }
        return ans;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值