All Paths From Source to Target

All paths from node 0 to n-1 in a DAG — DFS emitting paths.

Medium
Time O(2^n * n) Space O(n)
LeetCode
3 min read
backtracking graph dfs

Problem#

Given a DAG adjacency list (graph[i] is the out-neighbors of i), return all paths from node 0 to node n - 1.

Examples#

  • graph = [[1,2],[3],[3],[]][[0,1,3],[0,2,3]]

Constraints#

  • 2 <= n <= 15.

Approach#

DFS from 0; maintain a path stack. On reaching n - 1, emit. No “visited” set needed — the graph is a DAG, so no cycles.

Solution#

All Paths Source to Target
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> out;
vector<int> path = {0};
const int target = graph.size() - 1;
function<void(int)> dfs = [&](int u) {
if (u == target) { out.push_back(path); return; }
for (int v : graph[u]) {
path.push_back(v);
dfs(v);
path.pop_back();
}
};
dfs(0);
return out;
}
};

Editorial#

DAG → no need for visited tracking; the absence of cycles guarantees termination. Each path is emitted exactly once on hitting the target node. Worst case is exponential (2^n paths in a fully-connected DAG).

Complexity#

  • Time: O(2^n * n) worst case.
  • Space: O(n) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.