|
| 1 | +/** |
| 2 | + * Given a directed, acyclic graph of N nodes. Find all possible paths from |
| 3 | + * node 0 to node N-1, and return them in any order. |
| 4 | + * |
| 5 | + * The graph is given as follows: the nodes are0, 1, ..., graph.length - 1. |
| 6 | + * graph[i] is a list of all nodes j for which the edge (i, j) exists. |
| 7 | + * |
| 8 | + * Example: |
| 9 | + * Input: [[1,2], [3], [3], []] |
| 10 | + * Output: [[0,1,3],[0,2,3]] |
| 11 | + * Explanation: The graph looks like this: |
| 12 | + * 0--->1 |
| 13 | + * | | |
| 14 | + * v v |
| 15 | + * 2--->3 |
| 16 | + * There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. |
| 17 | + * |
| 18 | + * Note: |
| 19 | + * The number of nodes in the graph will be in the range [2, 15]. |
| 20 | + * You can print different paths in any order, but you should keep the order |
| 21 | + * of nodes inside one path. |
| 22 | + */ |
| 23 | + |
| 24 | +public class AllPathsFromSourceToTarget797 { |
| 25 | + public List<List<Integer>> allPathsSourceTarget(int[][] graph) { |
| 26 | + List<List<Integer>> res = new ArrayList<>(); |
| 27 | + if (graph == null || graph.length == 0) return res; |
| 28 | + int N = graph.length; |
| 29 | + backtrace(graph, 0, N-1, new ArrayList<>(), res, N); |
| 30 | + return res; |
| 31 | + } |
| 32 | + |
| 33 | + private void backtrace(int[][] graph, int current, int dest, List<Integer> path, List<List<Integer>> res, int N) { |
| 34 | + if (current == dest) { |
| 35 | + path.add(current); |
| 36 | + res.add(new ArrayList<>(path)); |
| 37 | + path.remove(path.size() - 1); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + path.add(current); |
| 42 | + for (int child: graph[current]) { |
| 43 | + backtrace(graph, child, N-1, path, res, N); |
| 44 | + } |
| 45 | + path.remove(path.size() - 1); |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | + public List<List<Integer>> allPathsSourceTarget2(int[][] graph) { |
| 50 | + List<List<Integer>> res = new ArrayList<>(); |
| 51 | + if (graph == null || graph.length == 0) return res; |
| 52 | + int N = graph.length; |
| 53 | + List<Integer> path = new ArrayList<>(); |
| 54 | + path.add(0); |
| 55 | + backtrace2(graph, 0, N-1, path, res, N); |
| 56 | + return res; |
| 57 | + } |
| 58 | + |
| 59 | + private void backtrace2(int[][] graph, int current, int dest, List<Integer> path, List<List<Integer>> res, int N) { |
| 60 | + if (current == dest) { |
| 61 | + res.add(new ArrayList<>(path)); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + for (int child: graph[current]) { |
| 66 | + path.add(child); |
| 67 | + backtrace2(graph, child, N-1, path, res, N); |
| 68 | + path.remove(path.size() - 1); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments