#797
All Paths From Source to Target
pupil · 400 · lc medium +24 · verified · 83.5% accepted · 7,618 likes · top 95%
Description
Given a directed acyclic graph (DAG) with n nodes labeled 0 through n - 1, enumerate all paths from node 0 to node n - 1. The result may be returned in any order.
The graph is described as follows: graph[i] lists all nodes reachable from node i via a direct edge (i.e., there is a directed edge from node i to each node in graph[i]).
Example 1:
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Example 2:
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
Code
1
2
3