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 nn - 1graphgraph[node]noden - 1
Example 1
Output: [[0,1,3],[0,2,3]]
Explanation: from 0 you can go to 1 or 2, and both lead to 3.
Example 2
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
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],[]][1,2]
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.
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][0, 1][0, 1, 3][0, 2, 3]
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, pathdfs(node)nodenextgraph[node]nextpathdfs(next)
Because dfsnextnext
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 nodegraph.length - 1path
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][0,1,2,3,4]
Java Solution
The method allPathsSourceTargetdfs
- First, create
, the list of finished routes, andpaths , the route so far, holding node 0. Then callpath .dfs(graph, 0, path, paths) - In
, check whetherdfs equalsnode . If it does, add a copy,graph.length - 1 , tonew ArrayList<>(path) and return.paths - Otherwise, a loop goes over each
innext . It addsgraph[node] tonext , callspath fordfs , and then takesnext off again withnext .path.remove(path.size() - 1) - When the first call to
returns, every route has been saved, anddfs returnsallPathsSourceTarget .paths
The main
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:
[[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]graph[0] = [4,3,1]
The fourth line, [[0, 2, 3]][[1,2],[],[3],[]][0, 1][[1],[],[]]
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)[[0], [0]][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
and the chain of unfinishedpath calls each hold one entry per node on the current route, and a route in a DAG never repeats a node.dfs
The general pattern is explained in