-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path797.java
More file actions
59 lines (50 loc) · 1.78 KB
/
797.java
File metadata and controls
59 lines (50 loc) · 1.78 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
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
path.add(0);
dfs(graph, res, path, 0);
return res;
}
private void dfs(int[][] graph, List<List<Integer>> res, List<Integer> path, int node) {
if (node == graph.length - 1) {
res.add(new ArrayList<Integer>(path));
return;
}
// acyclic, don't need to add visited
for (int next: graph[node]) {
path.add(next);
dfs(graph, res, path, next);
path.remove(path.size() - 1);
}
}
}
__________________________________________________________________________________________________
sample 39220 kb submission
class Solution {
private List<List<Integer>> allPath = new ArrayList<>();
private void dfs(int [][] graph, int curr, List<Integer> currPath)
{
if (curr == graph.length - 1)
{
List<Integer> path = currPath.stream()
.collect(Collectors.toList());
path.add(curr);
allPath.add(path);
return;
}
currPath.add(curr);
for (int neighbour: graph[curr])
{
dfs(graph, neighbour, currPath);
}
currPath.remove(new Integer(curr));
}
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
dfs(graph, 0, new ArrayList<>());
return allPath;
}
}
__________________________________________________________________________________________________