All Paths From Source to Target (LeetCode 797): Solution and Explanation
Given a directed acyclic graph as an adjacency list, list every path that starts at node 0 and ends at the last node, n - 1. The paths may be returned in any order.
Intuition
The problem asks for every path, not the shortest or the count, so the work is enumeration. Backtracking is the natural tool: walk forward one edge at a time and undo the step when you come back.
Keep one list, the current path. From its last node, try each outgoing edge: append the neighbour, explore from there, then pop it so the next edge starts from the same prefix.
Usually a graph DFS needs a visited set to avoid loops. A DAG has no cycles, so no walk can come back to a node already on the path, and every walk from 0 that reaches n - 1 is a distinct valid path.
Approach: DFS with backtracking
- Set
target = n - 1and start withpath = [0]. - In
dfs(node): ifnode == target, append a copy ofpathto the answer and return. - Otherwise, for each
nxtingraph[node]: appendnxttopath, calldfs(nxt), then popnxt. - Call
dfs(0)and return the collected paths.
Step-by-step example
graph = [[1,2],[3],[3],[]]
- Start at 0 with path [0]. Its first edge goes to 1, so the path becomes [0,1].
- Node 1 has one edge, to 3. The path becomes [0,1,3] and 3 is the target, so [0,1,3] is saved.
- Pop 3 and then 1, which brings the path back to [0]. Node 0's second edge goes to 2: path [0,2].
- From 2 the edge to 3 gives [0,2,3], which is saved. Everything is popped and the answer is [[0,1,3],[0,2,3]].
Code: Python, Java, C++
1class Solution:
2 def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
3 target = len(graph) - 1
4 paths, path = [], [0]
5
6 def dfs(node):
7 if node == target:
8 paths.append(path[:])
9 return
10 for nxt in graph[node]:
11 path.append(nxt)
12 dfs(nxt)
13 path.pop()
14
15 dfs(0)
16 return paths1class Solution {
2 public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
3 List<List<Integer>> paths = new ArrayList<>();
4 List<Integer> path = new ArrayList<>();
5 path.add(0);
6 dfs(graph, 0, path, paths);
7 return paths;
8 }
9
10 private void dfs(int[][] graph, int node, List<Integer> path, List<List<Integer>> paths) {
11 if (node == graph.length - 1) {
12 paths.add(new ArrayList<>(path));
13 return;
14 }
15 for (int nxt : graph[node]) {
16 path.add(nxt);
17 dfs(graph, nxt, path, paths);
18 path.remove(path.size() - 1);
19 }
20 }
21}1class Solution {
2public:
3 vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
4 vector<vector<int>> paths;
5 vector<int> path = {0};
6 dfs(graph, 0, path, paths);
7 return paths;
8 }
9
10private:
11 void dfs(vector<vector<int>>& graph, int node, vector<int>& path, vector<vector<int>>& paths) {
12 if (node == (int)graph.size() - 1) {
13 paths.push_back(path);
14 return;
15 }
16 for (int nxt : graph[node]) {
17 path.push_back(nxt);
18 dfs(graph, nxt, path, paths);
19 path.pop_back();
20 }
21 }
22};Time and space complexity
O(2^n * n)
A DAG on n nodes can have up to 2^(n-2) paths from 0 to n - 1 (when every node links to every later node), and copying each path costs O(n).
O(n)
The recursion depth and the current path are at most n, not counting the output itself.
Other approaches
BFS over partial paths (time O(2^n * n), space O(2^n * n))
Put [0] in a queue. Pop a path, and for each neighbour of its last node push a new path with the neighbour appended; paths ending at n - 1 go to the answer. Same output, but every partial path is a separate copy in memory.
Memoized paths from each node (time O(2^n * n), space O(2^n * n))
Compute allPaths(u) = for each neighbour v, [u] + every path in allPaths(v), caching the result for each node. Shared suffixes are computed once, though building the final lists still costs the size of the output.
Common mistakes
- Appending
pathitself instead of a copy. Every saved entry then points to the same list, which ends up empty after backtracking. - Forgetting to pop after the recursive call, so later branches start from a wrong prefix.
- Adding a visited set. It is unnecessary in a DAG and wrong if it is never cleared, because two different paths may pass through the same node.
- Assuming node n - 1 has no outgoing edges and skipping the target check. Check for the target before exploring further.
Frequently asked questions
Why is there no visited set?
The graph is acyclic, so a DFS can never return to a node on its current path. Different paths may share nodes, and marking nodes as visited globally would wrongly cut those paths off.
Does the order of the output matter?
No. Any order of the paths is accepted. Each path itself must list nodes in order from 0 to n - 1.
Can the answer be empty?
Yes. If no sequence of edges leads from 0 to n - 1, there are no paths and the answer is an empty list.
Why is the worst case exponential?
When every node has an edge to every later node, each of the n - 2 middle nodes can be in or out of a path, giving 2^(n-2) paths. With n at most 15 that is only 8192 paths.