1+ package com .concept .scala .leetcode_30days_challenge_July2020
2+
3+ /** **
4+ * Day 24
5+ *
6+ * @todo Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
7+ * The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
8+ * @example 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+ * @note 1.The number of nodes in the graph will be in the range [2, 15].
18+ * 2.You can print different paths in any order, but you should keep the order of nodes inside one path.
19+ *
20+ */
21+ object AllPathsFromSourceToTarget {
22+ def main (args : Array [String ]): Unit = {
23+ val graph : Array [Array [Int ]] = Array (Array (1 , 2 ), Array (3 ), Array (3 ), Array ())
24+ println(allPathsSourceTarget(graph).mkString(" ," ))
25+ }
26+
27+ /**
28+ * 26 / 26 test cases passed.
29+ * Status: Accepted
30+ * Runtime: 828 ms
31+ * Memory Usage: 54.7 MB
32+ *
33+ */
34+ def allPathsSourceTarget (graph : Array [Array [Int ]]): List [List [Int ]] = {
35+
36+ def paths (source : Int , target : Int ): List [List [Int ]] = if (source == target) List (List (target)) else (for (n <- graph(source); p <- paths(n, target)) yield source :: p).toList
37+
38+ paths(0 , graph.length - 1 )
39+
40+ }
41+ }
0 commit comments