Problem 567965 · medium · Level 05 Advanced Algorithms & Graphs

Every Route to the Last Node

graphs · DFS · backtracking · DAG

A directed acyclic graph with n nodes 0 .. n-1 is given as a list of lists: graph[i] holds the nodes that node i has an edge to. Return every path from node 0 to node n-1, each path as a list of node labels. The paths may be returned in any order.

Examples

Input:  graph = [[1,2,3],[3],[1],[]]
Output: [[0,1,3],[0,2,1,3],[0,3]]

Input:  graph = [[1,3],[4],[4],[2,1],[]]
Output: [[0,1,4],[0,3,1,4],[0,3,2,4]]

Constraints

  • 1 <= n <= 18; the graph has no cycles.
  • Target O(paths * n) time; each path is reported once.

Goals

  • Enumerate paths with a DFS that carries the current path
  • Recognise that a DAG needs no visited set for path enumeration
Starting Python…