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;
}
}