Given a directed acyclic graph (DAG) with n nodes labeled from 0 to n-1, find all possible paths from the source node 0 to the target node n-1.
The graph is represented as an adjacency list where graph[i] contains all nodes you can reach directly from node i. Since this is a DAG, there are no cycles, which guarantees that our path-finding will eventually terminate.
Goal: Return all possible paths from node 0 to node n-1 in any order.
Example: If we have a graph [[1,2],[3],[3],[]], this represents:
- Node 0 can go to nodes 1 and 2
- Node 1 can go to node 3
- Node 2 can go to node 3
- Node 3 has no outgoing edges (target)
Input & Output
Visualization
Time & Space Complexity
In worst case, we might have 2^N paths (exponential), and each path can be up to N nodes long
Space for storing all paths, plus recursion stack depth of at most N
Constraints
- n == graph.length
- 2 β€ n β€ 15
- 0 β€ graph[i][j] < n
- graph[i][j] != i (i.e., there will be no self-loops)
- All the elements of graph[i] are unique
- The input graph is guaranteed to be a DAG