-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAll_797.java
80 lines (70 loc) · 2.2 KB
/
All_797.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.*;
class All_797 {
// My solution: DFS/Backtrack
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
int n = graph.length;
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
path.add(0);
backtrack(res, path, 0, n - 1, graph);
return res;
}
private void backtrack(List<List<Integer>> res, List<Integer> path, int start, int end, int[][] graph) {
if (start == end) {
res.add(new ArrayList<>(path));
} else {
for (int neighbor : graph[start]) {
path.add(neighbor);
backtrack(res, path, neighbor, end, graph);
path.remove(path.size() - 1);
}
}
}
// My solution: BFS
/*
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
int n = graph.length;
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
path.add(0);
Deque<LinkedList<Integer>> q = new ArrayDeque<>();
q.add(path);
while (!q.isEmpty()) {
LinkedList<Integer> ls = q.removeFirst();
if (ls.getLast() == n - 1) {
res.add(ls);
} else {
for (int neighbor : graph[ls.getLast()]) {
ls.add(neighbor);
q.add(new LinkedList<>(ls));
ls.removeLast();
}
}
}
return res;
}
*/
// Standard solution: Recursion
/*
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
return solve(graph, 0);
}
public List<List<Integer>> solve(int[][] graph, int node) {
int N = graph.length;
List<List<Integer>> ans = new ArrayList();
if (node == N - 1) {
List<Integer> path = new ArrayList();
path.add(N-1);
ans.add(path);
return ans;
}
for (int nei: graph[node]) {
for (List<Integer> path: solve(graph, nei)) {
path.add(0, node);
ans.add(path);
}
}
return ans;
}
*/
}