Problem Statement
All Paths From Source to Target
You are given a map of one-way streets. There are n places, labeled 0 up to n-1. The map is a list: graph[i] is the list of places you can travel to directly from place i. The arrows only go one direction (a directed graph), and there is no way to loop back to where you started (acyclic, meaning no cycles). A graph like this, with one-way arrows and no loops, is called a directed acyclic graph, or DAG. Your job is to find every possible path that starts at place 0 and ends at the last place, n-1. Because there are no loops to get stuck in, we can just try every route and write down each one that reaches the end.
Signals to notice
Brute force first
Not applicable — enumeration IS the problem. But in a DAG, no cycles means finite paths. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
DFS/backtracking: from the source, explore each neighbor recursively. When you reach the target, record the path. Since it's a DAG, no visited set is needed. worst case. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on graph=[[1,2],[3],[3],[]]
dfs(0,[0]): 0!=3, neighbors=[1,2] -> push 1, recurse dfs(1,[0,1]): 1!=3, neighbors=[3] -> push 3, recurse dfs(3,[0,1,3]): 3==target -> record [0,1,3]; pop 3 -> [0,1]; pop 1 -> [0] dfs(0): push 2 -> [0,2], recurse dfs(2,[0,2]): 2!=3, neighbors=[3] -> push 3, recurse dfs(3,[0,2,3]): 3==target -> record [0,2,3]; pop 3 -> [0,2]; pop 2 -> [0] loop over node 0 done return result=[[0,1,3],[0,2,3]]
What must stay true
In a DAG, every path from source to target is finite and non-repeating. DFS naturally enumerates all paths without needing cycle detection. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
function dfs(node, path):
if node == n-1: record copy of path; return
for nei in graph[node]:
path.append(nei); dfs(nei, path); path.pop()
dfs(0, [0]); return resultPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Adding a visited set — in a DAG, you WANT to visit the same node via different paths. A visited set would prevent finding valid alternative paths. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.