All Paths From Source to Target

Try to solve the All Paths From Source to Target problem.

Statement

You are given a directed acyclic graph (DAG) with nn nodes, labeled from 00 to n1n - 1. The graph is represented as an adjacency list, where graph[i] is a list of all nodes to which node i has a directed edge to.

Your task is to find all possible paths from node 00 (the source) to node n1n - 1 (the target) and return them as a list of paths. Each path should be represented as a list of node indexes.

Note: You may return the answer in any order.

Constraints:

  • 22 \leq nn 15\leq 15

  • 00 \leq graph[i][j] << nn

  • All nodes in graph[i] are unique.

  • The graph is guaranteed to be a DAG (no cycles).

  • There are no self-loops (i.e., graph[i] does not contain i).

Examples

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.