Skip to content

All Paths From Source to Target

MediumBacktracking
Decode it first. Clues, constraints, pattern and plan before any code.

You are given a directed acyclic graph (no cycles) with n nodes labelled 0 to n - 1, as an adjacency list: graph[i] lists the nodes you can go to directly from node i. Return every path from node 0 to node n - 1, in any order. Each path is the list of nodes it visits.

graph = [[1, 2], [3], [3], []]
→  [[0, 1, 3], [0, 2, 3]]
 
graph = [[4, 3, 1], [3, 2, 4], [3], [4], []]
→  [[0, 4], [0, 3, 4], [0, 1, 3, 4], [0, 1, 2, 3, 4], [0, 1, 4]]

Constraints

  • 2 <= n <= 15
  • 0 <= graph[i][j] < n
  • The graph has no cycles and no self-loops.