Problem 930
All Paths From Source to Target
Medium · 20 pts · Graph, Depth-First Search, Backtracking
Problem
A directed acyclic graph has N nodes numbered 0 to N - 1. Find every path from node 0 to node N - 1. Print how many paths there are, then each path as its node numbers separated by spaces, with the paths sorted in lexicographic order (compare node numbers one by one). Because the graph has no cycles, a plain depth-first search that records the current path never loops.
Input
The first line contains N. Line i + 1 describes node i: the number of outgoing edges, followed by their targets.
Output
Print the number of paths, then each path on its own line in lexicographic order.
Constraints
2 <= N <= 15; the graph is acyclic and has no self loops or repeated edges
Example input
4 2 1 2 1 3 1 3 0
Example output
2 0 1 3 0 2 3
Explanation
With edges 0→1, 0→2, 1→3 and 2→3, the paths from 0 to 3 are 0 1 3 and 0 2 3, so the output is 2 followed by these two lines.