All Paths From Source to Target

List every route from the first node to the last in a graph whose edges go one way and never loop back.

A graph has n nodes, numbered 0 to n - 1, joined by one-way edges, and no route through it ever comes back to a node it has already passed. It is given as an array graph, where graph[node] lists the nodes you can go to directly from node. Return every path from node 0 to node n - 1, in any order.

Example 1
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: from 0 you can go to 1 or 2, and both lead to 3.
Example 2
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
Solution

The Idea

Picture a few crossroads joined by one-way streets, laid out so that no street ever leads you back to a crossroads you have already passed. You stand at crossroads 0 and want to write down every route to the last one. That is this problem: the crossroads are the nodes and the one-way streets are the edges.

A graph like this, where every edge points one way and no route can loop back, is called a directed acyclic graph, or DAG for short. "Directed" is the one-way part, and "acyclic" means without loops.

Look at Example 1, graph = [[1,2],[3],[3],[]]. The first entry, [1,2], says the streets out of node 0 go to 1 and 2. The next two entries both say 3, and the last entry is empty, so node 3 has no way out. Keeping, for each node, the list of nodes it leads to is called an adjacency list, and the input already comes in that form. Following the arrows gives two routes: 0, 1, 3 and 0, 2, 3.

Example 2 branches more. Node 0 has three ways out, node 1 has three more, and the five routes in its output share their first steps. So how do we list every route without missing one or writing one down twice?

Think of a walker with a notebook. The walker writes down 0, takes the first way out, writes down the new node, and keeps going. On reaching the target, the walker copies the route into the answer. Then the walker steps back, crossing the last node off the notebook, until reaching a node with a way out not yet tried, and takes that one. Look at the picture below.

Left: the graph of Example 1, with arrows from 0 to 1 and 2, and from 1 and 2 to the target 3. Right: the choice tree of the path so far. From [0], go to 1 gives [0, 1], then go to 3 gives [0, 1, 3], which is saved. After the step back to [0], go to 2 gives [0, 2], then [0, 2, 3], which is saved too.

On the left is the graph of Example 1. The choice tree on the right shows what the notebook holds at each moment. From [0], "go to 1" makes [0, 1], and "go to 3" makes [0, 1, 3]. Node 3 is the target, so the label under its box says "reached 3: save". Node 1 has no other way out, so the walker crosses off 3 and 1: that is the dashed "step back to [0]" arrow. Then "go to 2" leads to [0, 2, 3], which is saved too.

Taking one street out of the current node, following the route to its end, and then crossing that street's node off the notebook to try the next street is called backtracking. Following one route as deep as it goes before trying another is called depth-first search, or DFS.

Will the walker ever go round in circles? No, because the graph has no loops. Every route ends, either at the target or at a node with no way out.

Solution Approach

Turning the walker into code means settling three things: how to keep the route so far, when a route is finished, and why the search needs no list of visited nodes.

Keeping the route so far

How does the code keep the notebook? One list, path, holds the nodes of the current route and starts out holding 0. A method dfs(node) stands for "find every route that continues from node". For each next in graph[node], it adds next to the end of path, calls dfs(next), and then removes that last node again.

Because dfs calls itself for next, each unfinished call stands for one crossroads on the current route. When the call for next returns, the loop in the call before it simply moves on to its next way out. That return is the walker's step back.

A simpler way would give each step its own copy of the route, so nothing has to be removed. That works too, but it copies the route at every street, while one shared list that grows and shrinks copies it only when a route is finished.

When a route is finished

When is a route complete? When node is the last node, graph.length - 1. The call then saves a copy of path into the answer and returns. It must be a copy, because the same list keeps changing as the search steps back and goes on.

What about a node with no way out that is not the target? Its loop has nothing to try, so its call returns without saving anything, and that route is dropped.

Why no visited list is needed

Searches on graphs with loops must remember which nodes they have visited, or they could go round a loop forever. A DAG has no loops, so every route ends without that list. Marking nodes as visited would even be wrong here. In Example 2, node 3 lies on three of the five routes: [0,3,4], [0,1,3,4] and [0,1,2,3,4]. Marking it after the first one would lose the other two.

Java Solution

The method allPathsSourceTarget and its helper dfs work in these steps:

  1. First, create paths, the list of finished routes, and path, the route so far, holding node 0. Then call dfs(graph, 0, path, paths).
  2. In dfs, check whether node equals graph.length - 1. If it does, add a copy, new ArrayList<>(path), to paths and return.
  3. Otherwise, a loop goes over each next in graph[node]. It adds next to path, calls dfs for next, and then takes next off again with path.remove(path.size() - 1).
  4. When the first call to dfs returns, every route has been saved, and allPathsSourceTarget returns paths.

The main method runs both examples, a graph of two nodes, a graph where node 1 has no way out, and a graph whose target cannot be reached. It then builds graphs where every node has an edge to every later node: it prints all routes for 5 nodes and only their number for 12.

Java
import java.util.ArrayList;
import java.util.List;

public class AllPathsSourceTarget {

    public static List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> paths = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        path.add(0);
        dfs(graph, 0, path, paths);
        return paths;
    }

    private static void dfs(int[][] graph, int node, List<Integer> path,
                            List<List<Integer>> paths) {
        if (node == graph.length - 1) {
            paths.add(new ArrayList<>(path));   // copy: path keeps changing after this
            return;
        }
        for (int next : graph[node]) {
            path.add(next);                     // go to next
            dfs(graph, next, path, paths);      // every path that continues from next
            path.remove(path.size() - 1);       // step back to node
        }
    }

    // every node has an edge to every later node
    static int[][] everyLaterNode(int n) {
        int[][] graph = new int[n][];
        for (int from = 0; from < n; from++) {
            graph[from] = new int[n - 1 - from];
            for (int to = from + 1; to < n; to++) {
                graph[from][to - from - 1] = to;
            }
        }
        return graph;
    }

    public static void main(String[] args) {
        System.out.println(allPathsSourceTarget(new int[][] {{1, 2}, {3}, {3}, {}}));
        System.out.println(allPathsSourceTarget(
                new int[][] {{4, 3, 1}, {3, 2, 4}, {3}, {4}, {}}));
        System.out.println(allPathsSourceTarget(new int[][] {{1}, {}}));
        System.out.println(allPathsSourceTarget(new int[][] {{1, 2}, {}, {3}, {}}));
        System.out.println(allPathsSourceTarget(new int[][] {{1}, {}, {}}));
        System.out.println(allPathsSourceTarget(everyLaterNode(5)));
        System.out.println(allPathsSourceTarget(everyLaterNode(12)).size());
    }
}

Running it prints:

Output
[[0, 1, 3], [0, 2, 3]]
[[0, 4], [0, 3, 4], [0, 1, 3, 4], [0, 1, 2, 3, 4], [0, 1, 4]]
[[0, 1]]
[[0, 2, 3]]
[]
[[0, 1, 2, 3, 4], [0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [0, 2, 3, 4], [0, 2, 4], [0, 3, 4], [0, 4]]
1024

The second line lists the five routes of Example 2 in the order the search finds them. [0, 4] comes first because 4 is first in graph[0] = [4,3,1], and every route through 1 comes last.

The fourth line, [[0, 2, 3]], comes from [[1,2],[],[3],[]]. Node 1 has no way out, so the call for 1 returns without saving [0, 1]. In [[1],[],[]] no edge reaches node 2 at all, and the fifth line is an empty list.

The sixth line has 8 routes for 5 nodes, and the last line says 1024 for 12 nodes. In these graphs each node between the first and the last is either on a route or not, so there are 2n - 2 routes: 23 = 8 and 210 = 1,024.

The copy in step 2 matters. With paths.add(path) instead, Example 1 prints [[0], [0]]. Both entries are then the same list, and by the time the search ends it has stepped back to [0].

Complexity

The cost follows the number of routes, since each one is built node by node and copied once when it reaches the target.

  • Time: O(2n ยท n) in the worst case, because a graph where every node has an edge to every later node has 2n - 2 routes, 1,024 for 12 nodes, and saving each one copies up to n nodes.
  • Space: O(n) besides the output, because path and the chain of unfinished dfs calls each hold one entry per node on the current route, and a route in a DAG never repeats a node.

The general pattern is explained in Backtracking Basics.