Given a directed graph as an adjacency list and two vertices source and target, return every simple directed path from source to target.
For this practice version, a simple path cannot repeat a vertex. This restriction makes the result finite even when the graph contains cycles. A path ends when it first reaches target.
Input
-
graph
: an array of adjacency lists. Vertices are labeled
0
through
graph.length - 1
;
graph[u]
lists the vertices reachable by one directed edge from
u
.
-
source
,
target
: valid vertex labels.
Output
Return an array of paths. Each path is an array of vertex labels including both endpoints. Sort the paths in lexicographic order by their vertex sequences, using the shorter sequence first if one is a prefix of another.
Constraints and Edge Cases
-
For this practice version,
1 <= graph.length <= 10
.
-
Adjacency lists may be unsorted but contain no repeated neighbors.
-
Directed cycles and self-loops are allowed. Neither permits a vertex to repeat within a returned path.
-
If
source == target
, return only the one-vertex path
[source]
.
-
If the target is unreachable, return an empty array.
-
Paths that share intermediate vertices are distinct when their complete vertex sequences differ.
Example 1
graph = [[2,1], [2,3], [1,3], []]
source = 0
target = 3
output = [[0,1,2,3], [0,1,3], [0,2,1,3], [0,2,3]]
The cycle between vertices 1 and 2 does not permit paths such as [0,1,2,1,3].
Example 2
graph = [[1], [0], [2]]
source = 0
target = 2
output = []
Vertex 2 cannot be reached from 0, regardless of the cycles in the graph.