 All Problems
All Paths From Source to Target
medium
graph
depth-first search
backtracking
dag
google
amazon
facebook

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.

Example 1:

Input:
4
1 2
3
3
Output:
0 1 3
0 2 3

Example 2:

Input:
4
4
3 1
3 2
3
Output:
0 4
0 3 2
0 1 3
0 1 2 3

Constraints:

  • n == graph.length
  • 2 ≤ n ≤ 15
  • 0 ≤ graph[i][j] < n
  • graph[i] does not contain i

Input format: First line: n. Then n lines — neighbors of node i (space-separated, empty line for no neighbors).

Output format: Each path on its own line, space-separated. Paths in lexicographic order.

Run to check your code against the sample cases, or submit to run every case