LeetCode 797 All Paths From Source to Target (dfs 链式前向星)

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1, and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

 

Example 1:

Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

Example 2:

Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]

Example 3:

Input: graph = [[1],[]]
Output: [[0,1]]

Example 4:

Input: graph = [[1,2,3],[2],[3],[]]
Output: [[0,1,2,3],[0,2,3],[0,3]]

Example 5:

Input: graph = [[1,3],[2],[3],[]]
Output: [[0,1,2,3],[0,3]]

 

Constraints:

  • n == graph.length
  • 2 <= n <= 15
  • 0 <= graph[i][j] < n
  • graph[i][j] != i (i.e., there will be no self-loops).
  • The input graph is guaranteed to be a DAG.

题目链接:https://leetcode.com/problems/all-paths-from-source-to-target/

题目大意:求DAG所有起点到终点的路径

题目分析:dfs即可,链式前向星建图

4ms,时间击败34.16%

class Solution {
    
    private class Edge {
        int to, nxt;
        Edge(int to, int nxt) {
            this.to = to;
            this.nxt = nxt;
        }
    }
    
    private class Graph {
        private int[] head;
        private int cnt;
        private Edge[] e;
        private int m;

        Graph(int n) {
            m = (n * (n - 1)) >> 1;
            e = new Edge[m];
            head = new int[n];
            Arrays.fill(head, -1);
            cnt = 0;
        }

        private void addEdge(int u, int v) {
            e[cnt] = new Edge(v, head[u]);
            head[u] = cnt++; 
        }

    }
    
    private void dfs(int u, int target, List<Integer> cur, List<List<Integer>> ans, Graph g) {
        if (u == target) {
            ans.add(new LinkedList<>(cur));
            return;
        }
        for (int i = g.head[u]; i != -1; i = g.e[i].nxt) {
            int v = g.e[i].to;
            cur.add(v);
            dfs(v, target, cur, ans, g);
            cur.remove(cur.size() - 1);
        }
    }

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> ans = new LinkedList<>();
        Graph g = new Graph(graph.length);
        for (int i = 0; i < graph.length; i++) {
            for (int j = 0; j < graph[i].length; j++) {
                g.addEdge(i, graph[i][j]);
            }
        }
        List<Integer> cur = new LinkedList<Integer>();
        cur.add(0);
        dfs(0, graph.length - 1, cur, ans, g);
        return ans;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值