Skip to content
Problem 797 · LeetCode 797(opens in a new tab)

All Paths From Source to Target

MediumBacktracking

You are given a directed graph with n nodes, numbered 0 to n − 1, that has no cycles. graph[i] lists the nodes that node i has an edge to.

Return every path that starts at node 0 and ends at node n − 1, as a list of node numbers. The paths may be returned in any order.

Example 1

Input:  graph = [[1,2],[2],[3],[]]
Output: [[0,1,2,3],[0,2,3]]
Why:    node 2 is reached from 0 directly or through 1
2 more examples and the constraints

Example 2

Input:  graph = [[1],[]]
Output: [[0,1]]
Why:    a single edge from the start to the end

Example 3

Input:  graph = [[3,1],[2,3],[3],[]]
Output: [[0,3],[0,1,2,3],[0,1,3]]
Why:    three ways to reach node 3

Constraints

  • 2 ≤ n ≤ 15
  • Each graph[i] holds distinct nodes, none equal to i
  • The graph has no cycles

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Queue of partial pathsO(2ⁿ · n)
  2. Backtracking DFSO(2ⁿ · n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 15 nodes, all edges forwardVerdict
Queue of partial pathsO(2ⁿ · n)
Works; copies every partial path
Backtracking DFSO(2ⁿ · n)
Best; copies only finished paths

n = number of nodes. The answer itself can hold 2ⁿ⁻² paths.

Edge cases to test

  • Two nodes. [[1],[]] gives the single path [[0,1]].
  • No route. If no edge chain reaches n − 1, as in [[1],[],[]], the answer is empty.
  • Dead ends. Branches that stop before the target add nothing; the walk pops back out of them.
  • Every edge forward. With an edge from every node to every later one, n = 15 gives 8,192 paths.
  • Edges into node 0. They are never used, since every path starts at 0 and the graph has no cycles.

Common mistakes

  • Saving path itself instead of a copy, so every saved path changes when the shared list is popped.
  • Forgetting to pop after the loop, which leaves old nodes on the path.
  • Adding a visited set across the whole search, which wrongly blocks a node that is reached by a second route.

How to talk through it

  1. 1Clarify. Is the graph guaranteed to have no cycles? Any order for the paths? How large can n be?
  2. 2Size the output. There can be 2ⁿ⁻² paths, so listing them is exponential whatever we do.
  3. 3Choose backtracking. DFS with one shared path: push on entry, pop on exit, copy at the target.
  4. 4Code it. A short recursive dfs; no visited set because there are no cycles.
  5. 5Test out loud. Run Example 1 aloud, a graph with no route, and a two-node graph before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?