← Visualizers
Graphs · Enumerating paths · anti-pattern LeetCode 797

All Paths From Source to Target / visualized

The input is a DAG, so a visited set is not merely unnecessary here — it is wrong. It silently drops every path that would have gone through a node some earlier path already used. Flip the toggle and watch the answers disappear one at a time.

Execution

idle
INVARIANT DAG Backtracking Invariant: A Directed Acyclic Graph contains no cycles. A node may legitimately belong to multiple distinct paths. Using a global visited set incorrectly drops valid paths. Only path state (path.add / path.removeLast) is needed.
Press Run to begin.
0 / 0
Speed

Java · running line

current node on the path target blocked by visited
INTERVIEW SCRIPT

How to Explain All Paths on a DAG to an Interviewer

1. The DAG Guarantee

"Because the graph is a Directed Acyclic Graph (DAG), any path moving along directed edges can never cycle back to an earlier vertex. Cycle guards are mathematically impossible to trigger."

2. The Global Visited Bug

"If you use a standard boolean[] visited that marks nodes without unmarking them, discovering path A → B → D will mark B as seen, permanently blocking any later path C → B → D!"

3. Backtracking Discipline

"The path list is mutable. Maintain the invariant: push $v$ into path before recursing into $v$, and execute path.remove(path.size() - 1) immediately upon returning."

4. Exponential Complexity Bound

"In the worst-case complete DAG, there are $2^{n-2}$ distinct paths, each of length up to $n$. Time and space are $O(2^n \cdot n)$, which is asymptotically optimal because every single path must be constructed and output."

O(2ⁿ·n) time — that is the size of the output, not waste  ·  a DAG cannot revisit a node within one path, so nothing needs marking; the undo that backtracking usually needs is just path.removeLast().