-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSourceToTarget.java
More file actions
61 lines (43 loc) · 1.52 KB
/
SourceToTarget.java
File metadata and controls
61 lines (43 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.*;
import java.io.*;
/*
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
*/
class SourceToTarget {
static List<List<Integer>> result;
static int n;
static void getPaths(List<List<Integer>> graph, int currNode, List<Integer> path){
if(currNode == n-1) {
result.add(new ArrayList<>(path));
return;
}
List<Integer> tempPath;
for(int k: graph.get(currNode)){
tempPath = new ArrayList<>(path);
tempPath.add(k);
getPaths(graph, k, tempPath);
}
}
public static void main(String[] args) throws IOException {
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
List<List<Integer>> graph = new ArrayList<>();
List<Integer> temp;
result = new ArrayList<>();
int i,j;
n = Integer.parseInt(infile.readLine());
for(i=0; i<n; i++){
String[] inp = infile.readLine().split(" ");
temp = new ArrayList<>();
for(String k: inp){
temp.add(Integer.parseInt(k));
}
graph.add(new ArrayList<>(temp));
}
temp = new ArrayList<>();
temp.add(0);
getPaths(graph, 0, temp);
System.out.println(result);
infile.close();
}
}