All Paths From Source to Target
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #797
Given a directed acyclic graph with nodes 0..n-1 (graph[i] lists the nodes i points to), return all paths from node 0 to node n-1, in any order.
Examples
text
graph = [[1,2],[3],[3],[]] → [[0,1,3],[0,2,3]]
graph = [[4,3,1],[3,2,4],[3],[4],[]]
→ [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]Hints
- In a DAG you can never return to a node already on the current path, so you don't need a visited set.
- Backtrack: push a node, recurse into its neighbors, pop.
Approach
DFS from 0 with a path list. On reaching n-1, record a copy. A visited set would be wrong here: a node can lie on several different paths, and we want all of them.
The number of paths can be exponential (up to 2^(n−2)), so the output size dominates: O(2ⁿ · n).
Complexity
Time: O(2ⁿ · n) worst case. Space: O(n) besides the output.
Python solution
def allPathsSourceTarget(graph):
target, res, path = len(graph) - 1, [], [0]
def dfs(u):
if u == target:
res.append(path[:])
return
for v in graph[u]:
path.append(v)
dfs(v)
path.pop()
dfs(0)
return resJavaScript solution
function allPathsSourceTarget(graph) {
const target = graph.length - 1, res = [], path = [0];
const dfs = (u) => {
if (u === target) { res.push([...path]); return; }
for (const v of graph[u]) { path.push(v); dfs(v); path.pop(); }
};
dfs(0);
return res;
}