All Simple Paths in an Undirected Graph
Problem statement
Build an undirected graph with nodes 0..n-1 from edges. Return every simple path from source to target.
A simple path repeats no node. Sort each adjacency list and return paths in depth-first lexicographic order.
Function
allSimplePaths(n: int, edges: int[][], source: int, target: int) → int[][]Examples
Example 1
n = 4edges = [[0,1],[1,3],[0,2],[2,3],[1,2]]source = 0target = 3return = [[0,1,2,3],[0,1,3],[0,2,1,3],[0,2,3]]DFS follows sorted neighbors and never repeats a node.
Constraints
1 <= n <= 15.- Edges are unique undirected pairs.
- Source and target are valid distinct nodes.