All paths from source to target
Challenge · Write code · about 20 min
Given a directed acyclic graph, return every path from source to target. Each path lists its nodes in order. The paths may come back in any order.
Example 1
Input:
[{"n":4,"edges":[[0,1],[0,2],[1,3],[2,3]],"directed":true},0,3]
Output:
[[0,1,3],[0,2,3]]
Two routes: through 1 and through 2.
Example 2
Input:
[{"n":5,"edges":[[0,1],[0,2],[0,3],[1,2],[2,4],[3,4]],"directed":true},0,4]
Output:
[[0,1,2,4],[0,2,4],[0,3,4]]
Three routes reach 4.
Constraints
- 1 ≤ n ≤ 15
- 0 ≤ source, target < n
- The graph is a DAG, so no path repeats a node.
Learn the idea first: Depth-first search, a visual lesson.
More Depth-first search problems
- DFS order Warm-up
- Back edge Warm-up
- Recursive and iterative DFS Standard
- Is there a path? Standard
- Cycle reachable from a node Standard