All Paths From Source to Target

You are given a directed acyclic graph of n nodes labeled 0 to n - 1 as an adjacency list: graph[i] lists every node you can reach from node i in one step. Return every path that starts at node 0 and ends at node n - 1, in any order.

30:00

All Paths From Source to Target
medium
Free written solution
Topics
Companies

You are given a directed acyclic graph of n nodes labeled 0 to n - 1 as an adjacency list: graph[i] lists every node you can reach from node i in one step. Return every path that starts at node 0 and ends at node n - 1, in any order.

Example 1:
Input: {"graph":[[1,2],[3],[3],[]]}
Output: [[0,1,3],[0,2,3]]
Constraints:
  • n==graph.lengthn == \text{graph.length}

  • 2≤n≤152 \leq n \leq 15

  • 0≤graph[i][j]<n0 \leq \text{graph}[i][j] < n

  • graph[i][j]≠i\text{graph}[i][j] \neq i (no self-loops)

  • All elements of graph[i]\text{graph}[i] are unique.

  • The input graph is guaranteed to be a DAG.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"graph":[[1,2],[3],[3],[]]}

The graph has 4 nodes. Every path must start at node 0 and end at node 3.

0source123target

path

0

paths found: 0

none yet

current node
on the DFS path
edge being backtracked
target n - 1
Variables
VariableValue
target3
path[0]
found0
DepthFunction Call
Stack empty
0/13