Problem 513519 · medium · Level 05 Advanced Algorithms & Graphs

Every Route Through a One-Way Flow Chart

backtracking · graphs · DAG · depth-first search

A flow chart has steps 0 .. n-1; nexts[i] lists the steps you may go to directly after step i. The arrows never form a loop. Return every route that starts at step 0 and ends at the last step n - 1, each as the list of steps visited. Routes may be returned in any order.

Examples

Input:  nexts = [[1, 2], [2], []]
Output: [[0, 1, 2], [0, 2]]

Input:  nexts = [[]]
Output: [[0]]
Explanation: the start is already the last step.

Input:  nexts = [[1], [], []]
Output: []
Explanation: step 2 cannot be reached.

Constraints

  • 1 <= n <= 14, the graph has no cycles, no repeated arrows
  • The number of routes is at most a few thousand.

Goals

  • Enumerate all paths in a directed acyclic graph with a path stack
  • Understand why a DAG needs no visited set for simple paths
Starting Python…