Skip to content

Commit 6f1f4a6

Browse files
authored
Merge pull request #185
add AllPathsFromSourceToTarget - Day 24
2 parents 2e2fca1 + 0c7999d commit 6f1f4a6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
 (0)